<!--
@Description:工单创建
@Last Modified by:zqy
@Last Modified time:2022-07-06 01:07:27
-->
<template>
  <div class="create-order">
    <ContentWrap v-loading="isLoading" element-loading-text="拼命加载中">
      <FormContainer :column="4" :disabled="comDisabled || orderType === 'view'">
        <el-form
          ref="formOrder"
          :model="formData"
          :rules="formRules"
          label-width="115px"
        >
          <el-form-item
            prop="buyChannel"
            label="购买渠道"
            :rules="[
              { required: true, message: '购买渠道不能为空', trigger: 'change' }
            ]"
          >
            <!--创建工单时： 来电弹屏和打开创建工单时默认值为电商(1) -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="PURCHASE_CHANNEL"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="formData.buyChannel"
              filterable
              @on-change="buyChannelHandle"
            ></CustomDictSelect>
          </el-form-item>

          <el-form-item
            prop="contactName"
            label="联系人"
            :rules="[
              { required: true, message: '联系人不能为空', trigger: 'change' }
            ]"
          >
            <el-input v-model.trim="formData.contactName" clearable />
          </el-form-item>
          <el-form-item
            prop="contactPhone"
            label="联系电话"
            :rules="[
              { required: true, message: '联系电话不能为空', trigger: 'change' },
              //{ pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系电话', trigger: 'change' }
            ]"
          >
            <el-input v-model.trim="formData.contactPhone" number clearable>
              <template slot="append">
                <svg-icon icon-class="shouji-solid" style="cursor:pointer;color:#00926d;" @click="contactTpSms()"></svg-icon>
                <SvgIcon icon-class="dianhuaboda-solid" style="cursor:pointer;color:#00926d;" @click.native.stop="callOutHandle()"></SvgIcon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            prop="channelType"
            label="联系渠道"
            :rules="[
              { required: true, message: '请选择联系渠道', trigger: 'change' }
            ]"
          >
            <el-select v-model="formData.channelType" filterable clearable>
              <el-option
                v-for="(list, index) of channelTypeOption.filter(e=>!showJoinIn||(showJoinIn && [1,'1',2,'2'].includes(e.dictCode)))"
                :key="index"
                :value="list.dictCode"
                :label="list.dictName"
              />
            </el-select>
          </el-form-item>
          <template v-if="isEC">
            <el-form-item
              prop="orderCode"
              label="平台订单号"
              :rules="[
                { required: isEC && !isConsult, validator: (r, v, c) => {
                  if (isEC && !isConsult) {
                    if (v === '' || v === null || v === undefined) {
                      c('请输入平台单号')
                    } else {
                      c()
                    }
                  } else {
                    c()
                  }
                }, trigger: 'change' }
              ]"
            >
              <SelectOrderList ref="selectOrderList" v-model="formData.orderCode" :buy-channel="formData.buyChannel" @change="handleOrderCodeChange" @on-confirm="handleOnConfirm"></SelectOrderList>
            </el-form-item>
            <el-form-item prop="ecOrderNumber" label="电商订单号">
              <el-input v-model.trim="formData.ecOrderNumber" clearable @clear="clearChange" @blur="handleEBusicontactEnter(formData.ecOrderNumber)" />
            </el-form-item>
          </template>
          <el-form-item v-else prop="orderCode" label="零售订单号">
            <!-- @keyup.enter.native="contactEnter(formData.orderCode)"  -->
            <el-input v-model.trim="formData.orderCode" clearable @clear="clearChange" @blur="contactEnter(formData.orderCode)" />
          </el-form-item>
          <el-form-item
            v-if="isEC"
            prop="nickname"
            label="顾客ID"
            :rules="[
              { required: isEC && !isConsult, validator: (r, v, c) => {
                if (isEC && !isConsult) {
                  if (v === '' || v === null || v === undefined) {
                    c('请输入顾客ID')
                  } else {
                    c()
                  }
                } else {
                  c()
                }
              }, trigger: 'change' }
            ]"
          >
            <el-input v-model.trim="formData.nickname" clearable />
          </el-form-item>
          <el-form-item v-if="formData.buyChannel==='1'" prop="onlinePlatformName" label="电商平台">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/platform/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              :value.sync="formData.onlinePlatformCode"
              :lable.sync="formData.onlinePlatformName"
              :params="{query:{code:formData.onlinePlatformCode},type:0}"
              @selectChange="onlinePlatformChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item v-if="formData.buyChannel==='1'" prop="onlineShopCode" label="电商店铺">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/shop/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              :must-pid="true"
              :parent-id="formData.onlinePlatformCode"
              :params="{query:{platformCode:formData.onlinePlatformCode},type:0}"
              :value.sync="formData.onlineShopCode"
              :lable.sync="formData.onlineShopName"
            ></SearchSelectPicker>
          </el-form-item>

          <el-form-item v-if="formData.buyChannel==='1'" prop="orderTime" label="下单时间">
            <el-date-picker
              v-model="formData.orderTime"
              type="datetime"
              placeholder="选择下单时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            v-if="formData.buyChannel==='1'"
            prop="deliveryTime"
            label="预约送货时间"
            :rules="[
              { required: false, message: '请选择预约送货时间', trigger: 'change' }
            ]"
          >
            <el-date-picker
              v-model="formData.deliveryTime"
              type="datetime"
              placeholder="选择预约送货时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            v-if="formData.buyChannel==='1'"
            prop="deliveryMethod"
            label="配送方式"
          >
            <!-- :rules="[
              { required: true, message: '请选择配送方式', trigger: 'change' }
            ]" -->
            <CustomDictSelect
              placeholder="请选择配送方式"
              dict-type-code="CC_DELIVERY_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              :echo-value.sync="formData.deliveryMethod"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            prop="officeCode"
            label="办事处"
            :rules="[
              { required: showJoinIn, message: '请选择办事处', trigger: 'change' }
            ]"
          >
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              :lable.sync="formData.officeName"
              @selectChange="officeSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="disCode" label="经销商">
            <!-- 未完结前可修改 -->
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeCode"
              :value.sync="formData.disCode"
              :lable.sync="formData.disName"
              :current-id.sync="formData.disId"
              clearable
              @selectChange="disSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="shopName" label="门店">
            <!-- 未完结前可修改 -->
            <!-- 1--正常营业；2--预停用；3--已停用；4--预营业；5--未开业停用；6--经营异常 -->
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/shop/page"
              placeholder="请选择"
              lable-name="shopName"
              value-name="shopCode"
              custom-name="customerName"
              :remote="false"
              :params="{query:{businessStatus: '1,2,6',status:1,customerCodes: formData.disCode},type:1}"
              :must-pid="true"
              :parent-id="formData.disCode"
              :value.sync="formData.shopCode"
              :lable.sync="formData.shopName"
              @selectChange="selectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="afterSalesCall" label="工单对接人联系电话">
            <el-autocomplete
              v-model="formData.afterSalesCall"
              popper-class="my-autocomplete"
              :popper-append-to-body="false"
              clearable
              :fetch-suggestions="afterCallSearchAsync"
              @blur="afterSalesCallChange"
              @input="afterSalesCallChange"
            >
              <template slot-scope="{ item }">
                <div class="tel" style="font-size: 12px">{{ item.value }}</div>
                <!-- <span class="name">{{ item.name }}</span> -->
              </template>
              <template slot="append">
                <svg-icon icon-class="shouji-solid" style="cursor:pointer;color:#00926d;" @click="contactTpSms(formData.afterSalesCall)"></svg-icon>
                <SvgIcon icon-class="dianhuaboda-solid" style="cursor:pointer;color:#00926d;" @click.native.stop="callOutHandle(formData.afterSalesCall)"></SvgIcon>
              </template>
            </el-autocomplete>
          </el-form-item>

          <!-- <el-form-item :span="24/5*2"></el-form-item> -->
          <el-form-item
            prop="provinceName"
            label="省"
            :rules="[
              { required: showJoinIn, message: '请选择省', trigger: 'change' }
            ]"
          >
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="id"
              method="get"
              :value.sync="formData.province"
              :lable.sync="formData.provinceName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            prop="cityName"
            label="市"
            :rules="[
              { required: showJoinIn, message: '请选择市', trigger: 'change' }
            ]"
          >
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="id"
              method="get"
              :must-pid="true"
              :parent-id="formData.province"
              :params="{query:{id:formData.province},type:0}"
              :value.sync="formData.city"
              :lable.sync="formData.cityName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="countyName" label="区/县">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="id"
              method="get"
              :must-pid="true"
              :parent-id="formData.city"
              :params="{query:{id:formData.city},type:0}"
              :value.sync="formData.county"
              :lable.sync="formData.countyName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="streetName" label="街道">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="id"
              method="get"
              :must-pid="true"
              :parent-id="formData.county"
              :params="{query:{id:formData.county},type:0}"
              :value.sync="formData.street"
              :lable.sync="formData.streetName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="detailAddress" label="详细地址" :span="24">
            <el-input v-model="formData.detailAddress" type="textarea" :autosize="{minRows:1}" clearable resize="none" />
          </el-form-item>
          <el-form-item
            prop="businessType1"
            label="一级业务类型"
            :rules="[
              { required: true, message: '一级业务类型不能为空', trigger: 'change' }
            ]"
          >
            <el-select v-model="formData.businessType1" filterable clearable :loading="false" @change="businessTypeChange">
              <el-option
                v-for="(list, index) of businessType1Option"
                :key="index"
                :value="list.businessType"
                :label="list.businessTypeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="businessType2"
            label="二级业务类型"
            :rules="[
              { required: true, message: '二级业务类型不能为空', trigger: 'change' }
            ]"
          >
            <el-select v-model="formData.businessType2" filterable clearable @change="businessTypeTwoChange">
              <el-option
                v-for="(list, index) of businessType2Option"
                :key="index"
                :value="list.businessTypeTwo"
                :label="list.businessTypeTwoName"
              />
            </el-select>
          </el-form-item>
          <!-- 报修原因 repairsReason REPAIR_REASON -->
          <el-form-item
            v-if="repairsReasonRequired"
            key="repairsReason"
            prop="repairsReason"
            label="报修原因"
            :rules="[
              { required: repairsReasonRequired, validator: (r,v,c)=>{
                if(!repairsReasonRequired){
                  c()
                  return
                }
                if(!v||v.length===0){
                  c('请选择报修原因')
                } else {
                  c()
                }
              }, trigger: 'change' }
            ]"
          >
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="REPAIR_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.repairsReason"
              multiple
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            key="bpmDeptCode"
            prop="bpmDeptCode"
            label="业务部门"
            :rules="[
              { required: Number(formData.businessType2 || 0)!==42, message: '业务部门不能为空', trigger: 'change' }
            ]"
          >
            <!-- 二级业务类型(businessType2)为其他(42)时，业务部门不必填 -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="RESPONSIBLE_DEPARTMENT"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.bpmDeptCode"
              :echo-name.sync="formData.bpmDeptName"
            ></CustomDictSelect>

          </el-form-item>

          <!-- 63194   CC-SLM咨询加盟信息类工单数据同步（前端） -->
          <!-- 【咨询】-【加盟信息】类的工单，需要同步到SLM系统生成意向加盟客户数据。
          1.新增字段【是否有店面】【店面总面积】【意向经营业务】【意向客户分类】。
          字段展示在【业务部门】后面。
          2.当一二级业务类型为【咨询-加盟信息】时，展示以上新增的字段。
          3.当一二级业务类型为【咨询-加盟信息】时，
          CC的【CHANNEL_TYPE联系渠道】的可选项只有：1-电话、2-官网。
          CC的【CHANNEL_TYPE联系渠道】的【1-电话】
          对应SLM【意向客户来源渠道-CTM_POTENTIAL_CUSTOMER_SOURCE】的
          【B-4008】、CC的【CHANNEL_TYPE联系渠道】的
          【2-官网】对应SLM【意向客户来源渠道-CTM_POTENTIAL_CUSTOMER_SOURCE】的【A-官网】。
          4.当用户操作【完结】按钮的时候，就调用接口SLM的接口，
          将工单内的数据按照下表的对应关系给到SLM，SLM生成意向客户数据 -->
          <template v-if="showJoinIn">
            <el-form-item
              key="hasShop"
              prop="hasShop"
              label="是否有店面"
              :rules="[
                { required: false, message: '请选择是否有店面', trigger: 'change' }
              ]"
            >
              <CustomDictSelect
                placeholder="请选择"
                dict-type-code="ISOWN"
                bind-name="dictName"
                bind-value="dictCode"
                filterable
                :echo-value.sync="formData.hasShop"
              ></CustomDictSelect>
            </el-form-item>

            <el-form-item
              key="shopArea"
              prop="shopArea"
              label="店面总面积"
              :rules="[
                {
                  required: false,
                  validator: (r,v,c) => {
                    if(v===undefined || v==='' || v === null){
                      c()
                      return
                    }
                    if(/^\d\.\d+$|^[1-9]\d+\.\d+$|^\d+$/.test(v)){
                      c()
                    } else {
                      c('只能输入数字')
                    }
                  },
                  trigger: 'change' }
              ]"
            >
              <el-input v-model="formData.shopArea" placeholder="请输入" clearable></el-input>
            </el-form-item>

            <el-form-item
              key="bizType"
              prop="bizType"
              label="意向经营业务"
            >
              <CustomDictSelect
                placeholder="请选择"
                bind-name="dictName"
                bind-value="dictCode"
                filterable
                :echo-value.sync="formData.bizType"
                multiple
                :prop-enum="{
                  domainCode: 'marketing',
                  appCode: 'slm',
                  dictTypeCode: 'BIZ_TYPE'
                }"
              ></CustomDictSelect>
            </el-form-item>

            <el-form-item
              key="potentialType"
              prop="potentialType"
              label="意向客户分类"
            >
              <CustomDictSelect
                placeholder="请选择"
                bind-name="dictName"
                bind-value="dictCode"
                filterable
                :echo-value.sync="formData.potentialType"
                :prop-enum="{
                  domainCode: 'marketing',
                  appCode: 'slm',
                  dictTypeCode: 'CTM_TOBE_CUSTOMER_TYPE'
                }"
              ></CustomDictSelect>
            </el-form-item>
          </template>

          <el-form-item
            v-if="
              ([1,2].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 13 ) ||
                (formData.compensationCause.includes(4) |formData.compensationCause.includes('4'))
            "
            prop="serviceFeeType"
            label="服务费类型"
          >
            <!--
              当一级业务类型为咨询(1)，二级业务类型为服务费(13);
              当一级业务类型为投诉/纠纷(2)，二级业务类型为服务费(13)时;
              当赔付原因为服务费(4)时
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="SERVICE_FEE_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.serviceFeeType"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="[1,2,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 14 "
            prop="feeType"
            label="费用类型"
          >
            <!--
              当一级业务类型为咨询(1)，二级业务类型为费用常规(14)时;
              当一级业务类型为投诉/纠纷(2)，二级业务类型为费用常规(14)时;
              当一级业务类型为业务办理(3)，二级业务类型为费用常规(14)时;
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="EXPENSE_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.feeType"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="([1,2,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 15) ||
              (formData.handleScheme && (formData.handleScheme.includes(2) || formData.handleScheme.includes('2')))"
            prop="compensationCause"
            label="赔付原因"
            :rules="[
              { required: compensationCauseIsRequired,
                validator: (r,v,c)=>{
                  if(!compensationCauseIsRequired){
                    c()
                    return
                  }
                  if(!v||v.length===0){
                    c('赔付原因不能为空')
                  } else {
                    c()
                  }
                },
                trigger: 'change'
              }
            ]"
          >
            <!--
              当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时;
              当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时;
              当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时;
              当处理页面的处理方案选择【费用赔付(2)】时
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="COMPENSATION_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.compensationCause"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="[1,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 16"
            prop="invoiceSubBusiness"
            label="发票子业务"
          >
            <!--
              当一级业务类型为咨询(1)，二级业务类型为发票(16)时;
              当一级业务类型为业务办理(3)，二级业务类型为发票(16)时;
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="INVOICE_SUB_SERVICE"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.invoiceSubBusiness"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="Number(formData.businessType1 || 0)===2"
            prop="complaintCause"
            label="投诉原因"
            :rules="[
              { required: Number(formData.businessType2 || 0) !== 44, message: '请选择投诉原因', trigger: 'change' },
              { required: Number(formData.businessType2 || 0) !== 44, validator: (r,v,c)=>{
                if(Number(formData.businessType2 || 0) === 44){
                  c()
                  return
                }
                if(!v||v.length===0){
                  c('请选择投诉原因')
                } else {
                  c()
                }
              }, trigger: 'change' }
            ]"
          >
            <!--
              当一级业务类型为投诉/纠纷(2)时; 不同二级业务类型，投诉原因值列不同
              当一级业务类型为投诉/纠纷(2)时，投诉原因、投诉类型为必选 （当二级业务类型为 44产品质量 时不必选）
            -->
            <div>
              <el-select
                ref="customSelect"
                v-model="formData.complaintCause"
                multiple
                collapse-tags
                filterable
                clearable
                placeholder="请选择"
                style="width:100%"
                @clear="formData.compensationCause = []"
              >
                <el-option
                  v-for="(list, index) of complaintCauseOption"
                  :key="index"
                  :value="list.dictCode"
                  :label="list.dictName"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item
            v-if="Number(formData.businessType1 || 0)===2 && Number(formData.businessType2 || 0)===23 "
            prop="complaintObject"
            label="被投诉对象"
            :rules="[
              { required: true, message: '请选择被投诉对象', trigger: 'change' },
              { required: true, validator: (r,v,c)=>{
                if(!v||v.length===0){
                  c('请选择被投诉对象')
                } else {
                  c()
                }
              }, trigger: 'change' }
            ]"
          >
            <!--
              当一级业务类型为投诉/纠纷(2)，二级业务类型为服务态度(23)时展示此字段
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="OBJECT_OF_COMPLAINT"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.complaintObject"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>

          <el-form-item
            v-if="formData.complaintCause.includes(57) || formData.complaintCause.includes('57')"
            prop="customerDisapprovalCause"
            label="顾客不认可原因"
          >
            <!--
              当【投诉原因】为“顾客不认可处理方案导致(57)”时
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="CUSTOMER_DISAGREE_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.customerDisapprovalCause"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="Number(formData.businessType1 || 0)===2 "
            prop="complaintType"
            label="投诉类型"
            :rules="[
              { required: Number(formData.businessType1 || 0) === 2, message: '请选择投诉类型', trigger: 'change' }
            ]"
          >
            <!--
              当【一级业务类型】为“投诉/纠纷”(2)时
              当一级业务类型为投诉/纠纷(2)时，投诉原因、投诉类型为必选
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="COMPLAINTS_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.complaintType"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="[1,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 22"
            prop="deliveryNeed"
            label="送装需求"
            :rules="[{required: [22,'22'].includes(formData.businessType2), message: '请选择送装需求',trigger: 'change'}]"
          >
            <!--
              1.当【一级业务类型】为“咨询(1)”，【二级业务类型】为“送装服务(22)”时
              2.当【一级业务类型】为“业务办理(3)”，【二级业务类型】为“送装服务(22)”时
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="DELIVERY_INSTALL_DEMAND"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.deliveryNeed"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="[1,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0) === 22"
            prop="deliveryTime"
            label="预约送装服务时间"
            label-width="120px"
          >
            <!-- :rules="[
              { required: true, message: '请选择预约送装服务时间', trigger: 'change' }
            ]" -->
            <!-- 工单未完结前，均可对该字段进行修改，工单派单和抄送方均可对此字段进行修改 -->
            <el-date-picker
              v-model="formData.bookingServiceTime"
              type="datetime"
              placeholder="选择预约送装服务时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            v-if="!showJoinIn"
            prop="productProblem"
            label="产品问题"
            :rules="[
              {
                required: productProblemRequired,
                message: '请选择产品问题',
                trigger: 'change'
              }
            ]"
          >
            <!-- 一级业务类型为3业务办理时，二级业务类型为31报修时，产品问题为必选 -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="PRODUCT_PROBLEM"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.productProblem"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="formData.repairsReason.includes(7) || formData.repairsReason.includes('7')"
            prop="transportationLossType"
            label="运损类型"
            :rules="[
              {
                required:formData.repairsReason.includes(7) || formData.repairsReason.includes('7'),
                message: '运损类型不能为空',
                trigger: 'change'
              }
            ]"
          >
            <!--【产品问题】为运损(5)时才展示此字段 -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="TRANSPORT_DAMAGE_TYPE"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.transportationLossType"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="!showJoinIn"
            prop="productType"
            label="产品类型"
            :rules="[{ required: productTypeRequired, message: '请选择产品类型', trigger: 'change' }]"
          >
            <!--TODO:20220708 之后取消 当二级业务类型为31报修时,字段才为必填 ，更改为条件必填-->
            <el-select
              v-model="formData.productType"
              filterable
              clearable
              @change="productTypelChange"
            >
              <el-option
                v-for="(list, index) of productTypeOption"
                :key="index"
                :value="list.dictCode"
                :label="list.dictName"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!showJoinIn" prop="functionalSpace" label="功能空间">
            <el-select v-model="formData.functionalSpace" filterable clearable @change="functionalSpaceChange">
              <el-option
                v-for="(list, index) of functionalSpaceOption"
                :key="index"
                :value="list.dictCode"
                :label="list.dictName"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="!showJoinIn" prop="productCategory" label="产品品类">
            <el-select v-model="formData.productCategory" filterable clearable>
              <el-option
                v-for="(list, index) of productCategoryOption"
                :key="index"
                :value="list.dictCode"
                :label="list.dictName"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.productCode"
            prop="productCode"
            label="产品编码"
          >
            <!-- :rules="[{
              required:(Number(formData.buyChannel || 0)===1 && Number(formData.businessType2 || 0)===31) ||
                (Number(formData.businessType1 || 0)===1 && Number(formData.businessType2 || 0)===21) ,
              message: '产品编码不能为空',
              trigger: 'change'
            }]" -->
            <!--
              1.当购买渠道为电商(1)，二级业务类型为报修(31)时，产品编码和产品名称为必填项
              2.当一级业务类型为咨询(1)，二级业务类型为安装图纸(21)时，产品编码和产品名称为必填项。
            -->
            <el-input v-model="formData.productCode" disabled :maxlength="150" clearable @clear="clearProCodeChange" @blur="proCodeEnter(formData.productCode)" />
          </el-form-item>
          <el-form-item
            v-if="formData.productName"
            prop="productName"
            label="产品名称"
          >
            <!-- :rules="[{
              required:(Number(formData.buyChannel || 0)===1 && Number(formData.businessType2 || 0)===31) ||
                (Number(formData.businessType1 || 0)===1 && Number(formData.businessType2 || 0)===21) ,
              message: '产品名称不能为空',
              trigger: 'change'
            }]" -->
            <!--
              1.当购买渠道为电商(1)，二级业务类型为报修(31)时，产品编码和产品名称为必填项
              2.当一级业务类型为咨询(1)，二级业务类型为安装图纸(21)时，产品编码和产品名称为必填项。
            -->
            <el-input v-model="formData.productName" disabled :maxlength="150" />
          </el-form-item>
          <el-form-item v-if="formData.productMode" prop="productMode" label="产品型号">
            <el-input v-model="formData.productMode" disabled :maxlength="150" clearable />
          </el-form-item>
          <el-form-item
            prop="urgencyDegree"
            label="紧急程度"
            :rules="[
              { required: isEC, message: '请选择紧急程度', trigger: 'change' }
            ]"
          >
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="URGENCY_DEGREE"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.urgencyDegree"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="Number(formData.urgencyDegree || 0) === 2 || Number(formData.urgencyDegree || 0) === 3"
            prop="urgencyCause"
            label="紧急原因备注"
            :rules="[
              { required: Number(formData.urgencyDegree || 0) === 2 || Number(formData.urgencyDegree || 0) === 3,
                message: '紧急原因备注不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-input v-model="formData.urgencyCause" clearable maxlength="200" />
          </el-form-item>
          <!-- 当购买渠道为电商 buyChannel=1、
          业务类型businessType2为业务办理-报修31/换货19/拆装33/退货18/费用赔付15时， -->
          <!-- 产品信息内的：产品编码、产品名称、产品型号、处理数量为必填。至少要有一行产品数据 -->
          <el-form-item
            prop="productInfoDTOList"
            :span="24"
            label="产品信息"
            :rules="[
              { required: [1, '1'].includes(formData.buyChannel) && [15, 18, 19, 31, 33, '15', '18', '19', '31', '33'].includes(formData.businessType2),
                validator: validateProductListInfo,
                trigger: 'change'
              },
            ]"
          >
            <!-- <div> -->
            <!-- <span>产品信息</span> -->
            <ProductInfoList v-model="formData.productInfoDTOList" :p-code="formData.orderCode" :ec-order-number="formData.ecOrderNumber" :buy-channel="formData.buyChannel" :order-code="formData.orderCode"></ProductInfoList>
            <!-- </div> -->
          </el-form-item>
          <el-form-item
            prop="handleScheme"
            label="处理方案"
            :rules="[
              { required: true,
                message: '请选择处理方案',
                trigger: 'change'
              },
              { required: true,
                validator: (r,v,c)=>{
                  if(!v || v.length===0){
                    c('请选择处理方案')
                  } else {
                    c()
                  }
                },
                trigger: 'change'
              }
            ]"
          >
            <!--操作完结操作时为必选项-->
            <CustomDictSelect
              ref="handleScheme"
              placeholder="请选择"
              dict-type-code="PROCESS_METHOD"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :filter-handle="filterHandleScheme"
              :echo-value.sync="formData.handleScheme"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="showReturnsCause"
            prop="returnsCause"
            label="退/换货原因"
            :rules="[
              { required: true, message: '请选择退/换货原因', trigger: 'change' }
            ]"
          >
            <!--
              1.当一级业务类型为咨询(1)，二级业务类型为退货(18)时，展示该字段；
              2.当一级业务类型为咨询(1)，二级业务类型为换货(19)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为退货(18)时，展示该字段；
              4.当一级业务类型为业务办理(3)，二级业务类型为换货(19)时，展示该字段；
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="RETURN_REPLACEMENT_REASON"
              bind-name="dictName"
              bind-value="dictCode"
              filterable
              :echo-value.sync="formData.returnsCause"
            ></CustomDictSelect>
          </el-form-item>
          <el-form-item
            v-if="
              ([1,2,3].includes(Number(formData.businessType1 || 0)) && [14,15].includes(Number(formData.businessType2 || 0))) || (
                formData.handleScheme.includes(2) || formData.handleScheme.includes('2') ||
                formData.handleScheme.includes(3) || formData.handleScheme.includes('3')||
                formData.handleScheme.includes(11) || formData.handleScheme.includes('11')||
                formData.handleScheme.includes(12) || formData.handleScheme.includes('12')
              )
            "
            prop="paymentMode"
            label="支付方式"
          >
            <!--
              1.当一级业务类型为咨询(1)，二级业务类型为费用常规(14)时，展示该字段；
              2.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用常规(14)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为费用常规(14)时，展示该字段；
              4.当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时，展示该字段；
              5.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时，展示该字段；
              6.当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时，展示该字段；
              7.当处理方案为费用赔付(2)/赠品(3)/退差(11)/退款(12)时，展示该字段。
            -->
            <CustomDictSelect
              placeholder="请选择"
              dict-type-code="PAYMENT_MODE"
              bind-name="dictName"
              bind-value="dictCode"
              multiple
              collapse-tags
              filterable
              :echo-value.sync="formData.paymentMode"
              :def-value="[]"
            ></CustomDictSelect>
          </el-form-item>

          <el-form-item
            v-if="
              ([1,2,3].includes(Number(formData.businessType1 || 0)) && Number(formData.businessType2 || 0)===15)|| (
                formData.handleScheme.includes(2) || formData.handleScheme.includes('2') ||
                formData.handleScheme.includes(11) || formData.handleScheme.includes('11')||
                formData.handleScheme.includes(12) || formData.handleScheme.includes('12')
              )
            "
            prop="compensationFee"
            label="赔付金额"
            :rules="[
              {
                required: true,
                pattern:/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/,
                message: '请输入合法金额，最多两位小数',
                trigger:'change'
              }
            ]"
          >
            <!--
              1.当一级业务类型为咨询(1)，二级业务类型为费用赔付(15)时，展示该字段；
              2.当一级业务类型为投诉/纠纷(2)，二级业务类型为费用赔付(15)时，展示该字段；
              3.当一级业务类型为业务办理(3)，二级业务类型为费用赔付(15)时，展示该字段；
              4.当处理方案为费用赔付(2)/退差(11)/退款(12)时，展示该字段。
            -->
            <el-input v-model="formData.compensationFee" :maxlength="10" clearable />
          </el-form-item>

          <el-form-item
            v-if="(formData.paymentMode&&formData.paymentMode.some(e=>e===5||e==='5')) || (formData.handleScheme&&formData.handleScheme.some(e=>e===3||e==='3'))"
            prop="gift"
            label="赠品名称"
            :rules="[
              { required: true,
                message: '请输入赠品名称',
                trigger: 'change'
              }
            ]"
          >
            <!-- :rules="[
              { pattern: /^([\p{Han}\p{P}0-9])*$/, message: '只允许汉字、数字、标点符号', trigger: 'change' }
            ]" -->
            <!--
              1.当【支付方式】为赠品(5)时，展示该字段；
              2.手动录入，允许汉字、数字、标点符号
            -->
            <el-input v-model="formData.gift" :maxlength="100" clearable />
          </el-form-item>

          <el-form-item
            :span="24"
            prop="callContent"
            label="来电明细"
            :rules="[{ required: true, message: '请输入来电明细', trigger: 'change' }]"
          >
            <el-input
              v-model="formData.callContent"
              type="textarea"
              :autosize="{ minRows: 4 }"
            />
          </el-form-item>
          <el-form-item
            :span="24"
            prop="customerServiceOpinion"
            label="客服意见"
            :rules="[{ required: true, message: '请输入客服意见', trigger: 'change' }]"
          >
            <el-input
              v-model="formData.customerServiceOpinion"
              type="textarea"
              :autosize="{ minRows: 4 }"
            />
          </el-form-item>
          <el-form-item v-if="(page === 'call' || page === 'local') && pageState" label="附件">
            <!-- 上传附件 -->
            <DialogUpload :on-success="onSuccessHandle" multiple :destroy="isClear" :on-remove="removeHandle" :before-remove="beforeRemoveHandle" :on-change="onChangeHandle" :exist-file-list="annexList" :clear-file-list="isClear" />
          </el-form-item>
          <el-form-item v-if="orderType === 'edit'" :span="24">
            <div v-if="(page === 'call' || page === 'local') && pageState" class="button-container">
              <Button :disabled="!bottomAuth.save" type="primary" :loading="saveOrderLoading" @click="saveOrderHandler">保存</Button>
              <Button :disabled="!bottomAuth.office || disabledOfficeBtn" type="primary" :loading="assignDealerLoading" @click="assignDealer('office')">办事处</Button>
              <Button :disabled="!bottomAuth.dis" type="primary" :loading="assignDealerLoading" @click="assignDealer('dis')">经销商</Button>
              <!-- 责任部门 -->
              <DepartReciverDispatch ref="refDispatch" :button-auth="bottomAuth.shop" :enable-open="dispatchcOrderEnableOpen" @select-change="submitReciverDispatch" />
              <!-- 接收岗位 -->
              <ReceivePost v-model="formData.handlerPosts" :carbon-copy.sync="formData.ccPosts" is-create :work-order-data="formData" @on-confirm="handleReceivePostOnConfirm"></ReceivePost>
              <!-- 同步工单 -->
              <SyncOrder :button-auth="bottomAuth.sync" :call-content="formData.callContent" :customer="formData.customerServiceOpinion" :enable-open="syncOrderEnableOpen" @on-success="syncSuceess" />
              <!-- 完结 -->
              <Button :disabled="!bottomAuth.finish" type="primary" :loading="putFinishLoading" @click="putFinishClick">完结</Button>
              <!-- 异常上报 -->
              <AbnormalReport :button-auth="bottomAuth.abnormal" :order-id="formData.id" :work-order-code="reloadInfo.workOrderCode" :enable-open="abnormalReportEnableOpen" @on-success="abnormalSuccess" />
              <!-- <Care v-if="bottomAuth.care" text="关怀" title="关怀" @on-success="careSuccess" /> -->
            </div>
          </el-form-item>
          <el-form-item v-if="Array.isArray(processingList) && processingList.length" :span="24">
            <List :column="4" sep="：" label-width="100">
              <ListItem :span="24">
                <Title slot="content" class="custom-title order-top" title="工单流水记录" />
              </ListItem>
              <ListItem :span="24">
                <div slot="content" class="order-list">
                  <FlowOrder v-for="(f,i) in processingList" :key="i" :flow="f" />
                </div>
              </ListItem>
            </List>
          </el-form-item>
        </el-form>
      </FormContainer>
    </ContentWrap>
    <Dialog></Dialog>
    <CallOut ref="callOut"></CallOut>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import Button from '@/components/Button'
import DialogUpload from '@/components/Upload/DialogUpload'
import FormContainer from '@/components/FormContainer'
import AbnormalReport from '../components/AbnormalReport'
import DepartReciverDispatch from './components/DepartReciverDispatch'
import SyncOrder from './components/SyncOrder'
import Dialog from './components/Dialog'
// import Care from './components/Care'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import CustomDictSelect from '@/components/CustomDictSelect'
import Title from '@/components/Title'
import SelectOrderList from './components/SelectOrderList'
import ProductInfoList from './components/ProductInfoList'
import ReceivePost from '../components/ReceivePost'
import { List, ListItem } from '@/components/List'
import FlowOrder from '../components/FlowOrder'
import { parseTime } from '@/utils/'
import { getDictByType } from '@/api/dataDict'
import { searchBusinessByChannel, searchBusinessTwoByChannel } from '@/api/ChannelBusinessRel'
import { searchBusinessDefaultDept } from '@/api/BusinessDepartRel'
import { postWorkOrderRecord, getWorkOrderByCode, getByIdWorkOrderRecord, postDispatch, putFinish, deleteAnnex, getDealerMatch, productInfoByPCode } from '@/api/workOrder'
import { getRetailDetail } from '@/api/topInfo'
// getOfficeDetail, getOrderList
import {
  getAdminiDiv,
  getOrderDetailPCode,
  getMscInfoShop,
  getDealerInfo,
  getStoreInfoB2CECO,
  getOfficeDetail, getProductInfo,
  electronicCheck
} from '@/api/mscInfo'
import { getShopAfterInfo } from '@/api/shopAfter'
import { ArrayFormat } from '@/utils/params-format'
import { getHaveWorkOrder, getPlateCodeByEcCode, checkDistributorByDisCode } from '@/api/workOrder'
import { PSCMap } from './productSpaceCategory' // 产品=>功能空间=>产品分类映射数据
import { TCCMap } from './businessType2ComplaintCause' // 二级业务类型=>投诉原因映射数据
import { json2FormData } from '@/utils'

const officeCode = [
  { required: true, message: '办事处不能为空', trigger: 'change' }
]
const disCode = [
  { required: true, message: '经销商不能为空', trigger: 'change' }
]
// const afterSalesCall = [
//   { required: true, message: '售后联系电话不能为空', trigger: 'change' },
//   { pattern: /^1\d{10}$/, message: '请输入正确的联系电话', trigger: 'change' }
// ]
// const callContent = [
//   { required: true, message: '来电明细不能为空', trigger: 'change' }
// ]
const handleSchemeRule = [
  { required: true, message: '处理方案不能为空', trigger: 'change' }
]
// const customerServiceOpinion = [
//   { required: true, message: '客服意见不能为空', trigger: 'change' }
// ]

export default {
  name: 'CreateOrder',
  components: {
    ContentWrap,
    Button,
    FormContainer,
    DialogUpload,
    AbnormalReport,
    SyncOrder,
    DepartReciverDispatch,
    SearchSelectPicker,
    CustomDictSelect,
    Title,
    List,
    ListItem,
    FlowOrder,
    Dialog,
    SelectOrderList,
    ProductInfoList,
    ReceivePost
  },
  props: {
    orderData: {
      type: Object,
      default: () => ({})
    },
    customerName: {
      type: String,
      default: ''
    },
    callTel: {
      type: String,
      default: ''
    },
    getRecordIdFun: {
      type: Function,
      default: undefined
    },
    recordId: {
      type: String,
      default: ''
    },
    // call 通话界面操作成功后，隐藏所有按钮; local 当前界面
    page: {
      type: String,
      default: 'local'
    },
    // 是否全部禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 外呼回访相关
    taskData: {
      type: Object,
      default: () => {}
    },
    visitForm: {
      type: Object,
      default: () => {}
    },
    isTask: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isLoading: false,
      channelTypeOption: [], // 联系渠道下拉数据
      businessType1Option: [], // 业务类型1下拉数据
      businessType2Option: [], // 业务类型2下拉数据
      onlinePlatformOption: [], // 电商平台下拉数据
      onlineShopOption: [], // 电商店铺下拉数据
      productTypeOption: [], // 产品类型下拉数据
      functionalSpaceOption: [], // 当前可选功能空间下拉数据
      functionalSpaceStore: [], // 全部功能空间
      productCategoryOption: [], // 当前可选产品品类下拉数据
      productCategoryStore: [], // 全部产品品类
      complaintCauseOption: [], // 当前投诉原因下拉数据
      complaintCauseStore: [], // 所有投诉原因数据
      provinceNameOption: [], // TODO：待定是否移除
      cityNameOption: [], // TODO：待定是否移除
      countyNameOption: [], // TODO：待定是否移除

      shopCallTel: [], // 联系电话列
      processingList: [], // 工单流水记录数据

      formData: {
        id: '',
        contactName: '', // 联系人
        contactPhone: '', // 联系电话
        nickname: '', // 顾客id
        onlinePlatformCode: '', // 电商平台编码
        onlinePlatformName: '', // 电商平台
        onlineShopCode: '', // 电商店铺编码
        onlineShopName: '', // 电商店铺
        orderCode: '', // 平台单号
        ecOrderNumber: '', // 电商订单编号
        orderTime: '', // 下单时间
        deliveryTime: '', // 预约送货时间
        deliveryMethod: '', // 配送方式
        officeCode: '', // 办事处编码
        officeName: '', // 办事处
        disId: '', // 经销商ID
        disCode: '', // 经销商编码
        disName: '', // 经销商
        shopCode: '', // 门店编码
        shopName: '', // 门店
        afterSalesCall: '', // 售后联系人电话
        province: '', // 省代码
        provinceName: '', // 省名
        city: '', // 市编码
        cityName: '', // 市
        county: '', // 区县编号
        countyName: '', // 区、县
        street: '', // 街道编码
        streetName: '', // 街道
        detailAddress: '', // 详细地址
        urgencyDegree: '', // 紧急程度:默认1
        urgencyCause: '', // 紧急原因备注
        buyChannel: '', // 购买渠道
        channelType: '', // 联系渠道
        businessType1: '', // 业务类型1
        businessType1Name: '', // 业务类型名称
        businessType2: '', // 业务类型2
        businessType2Name: '', // 业务类型2名称
        repairsReason: [], // 报修原因
        bpmDeptCode: '', // 责任部门编码
        bpmDeptName: '', // 责任部门
        serviceFeeType: [], // 服务费类型
        feeType: [], // 费用类型
        compensationCause: [], // 赔付原因
        invoiceSubBusiness: '', // 发票子业务
        complaintCause: [], // 投诉原因
        complaintObject: [], // 投诉对象
        customerDisapprovalCause: [], // 顾客不认可原因
        complaintType: '', // 投诉类型
        deliveryNeed: '', // 送装需求
        bookingServiceTime: '', // 预约送装服务时间
        returnsCause: '', // 退换货原因
        transportationLossType: '', // 运损类型
        productType: '', // 产品类型
        functionalSpace: '', // 功能空间
        productCategory: '', // 产品品类
        productProblem: [], // 产品问题
        productMode: '', // 产品型号
        productCode: '', // 产品编码
        productName: '', // 产品名称
        handleScheme: ['1'], // 处理方案
        paymentMode: [], // 支付方式
        compensationFee: '', // 赔付金额
        gift: '', // 赠品名称
        callContent: '', // 来电明细
        customerServiceOpinion: '', // 客服意见
        patchCode: '', // 补件单号
        productInfoDTOList: [], // 产品信息
        // 加盟信息
        hasShop: '', // 是否有门店
        shopArea: '', // 门店总面积
        bizType: [], // 意向加盟业务类型
        potentialType: '' // 客户分类
      },
      formRules: {
        officeCode: [],
        disCode: [],
        // callContent,
        // customerServiceOpinion,
        handleScheme: []
      },
      // 上传附件
      uploadShow: false,
      isClear: false,
      annexList: [],
      reloadInfo: {
        workOrderCode: ''
      },
      // 预览图片
      previewShow: false,
      imageList: [],

      saveOrderLoading: false, // 是否保存操作加载中
      putFinishLoading: false, // 是否完结操作加载中
      assignDealerLoading: false, //

      // 其他系统配送类型与cc系统配送类型对应关系
      // 电商
      serMap: {
        1: '2', // 自提
        0: '4', // 送装
        2: '5' // 快递
      },
      // 门店
      delMap: {
        2: '1', // 自提
        1: '3' // 送装
      },
      orderType: 'edit',
      // 操作按钮权限--销售三部、电商运营
      bottomAuth: {
        save: false, // 保存
        office: false, // 办事处
        dis: false, // 经销商
        shop: false, // 责任部门
        finish: false, // 完结
        sync: false, // 同步工单
        abnormal: false, // 异常上报
        care: false // 关怀
      }, // 按钮权限是否可用
      // 通话弹屏请求状态
      pageState: true,
      // 当前通话记录id
      dRecordId: null,
      // 禁止编辑
      disabled1: false
    }
  },
  computed: {
    // 是电商
    isEC() {
      return this.formData.buyChannel === '1' || this.formData.buyChannel === 1
    },
    // 一级业务类型 为咨询 平台订单号 顾客id
    isConsult() {
      return this.formData.businessType1 === '1'
    },
    // 赔付原因是否必填
    compensationCauseIsRequired() {
      return ([3, '3'].includes(this.formData.businessType1) && [15, '15'].includes(this.formData.businessType2)) || (this.formData.handleScheme && this.formData.handleScheme.some(e => e === 2 || e === '2'))
    },
    // 退换货原因
    showReturnsCause() {
      let t = ([1, 3, '1', '3'].includes(this.formData.businessType1) && [18, 19, '18', '19'].includes(this.formData.businessType2))
      t = t || (this.formData.handleScheme && this.formData.handleScheme.some(e => [9, 10, 14, '9', '10', '14'].includes(e)))
      return t
    },
    // 禁止编辑
    comDisabled() {
      return this.disabled || this.disabled1
    },
    // 53959   服务工单：产品问题历史数据处理、新增报修原因字段、退换货原因调整
    // 1.当一级业务类型为业务办理、二级业务类型为报修时，【产品问题】为必填；
    // 2.当一级业务类型为投诉/纠纷、二级业务类型为产品质量时，【产品问题】为必填；
    // 投诉/纠纷 2
    // 业务办理 3
    // 报修 31
    // 产品质量 44
    productProblemRequired() {
      const t1 = [3, '3'].includes(this.formData.businessType1) && this.repairsReasonRequired
      const t2 = [2, '2'].includes(this.formData.businessType1) && [44, '44'].includes(this.formData.businessType2)
      return t1 || t2
    },
    // 53959   服务工单：产品问题历史数据处理、新增报修原因字段、退换货原因调整
    // 3.所有报修类工单都增加报修原因字段，且为必填；
    repairsReasonRequired() {
      return [31, '31'].includes(this.formData.businessType2)
    },
    // 电商-售中客服服务科
    isSMCSD() {
      return this.$inGroup('32')
    },
    // 是否新建
    isCreate() {
      const query = this.$route.query
      return !(query.workOrderNo || query.id)
    },
    // 禁用办事处
    disabledOfficeBtn() {
      // 57671   【办事处】按钮操作限制
      // 操作办事处的时候如果购买渠道-2电商，
      // 一级业务类型-1咨询，二级业务类型-45物流进度。这个条件集合，办事处按钮置灰。不可操作。
      const { buyChannel, businessType1, businessType2 } = this.formData
      return [1, '1'].includes(buyChannel) && [1, '1'].includes(businessType1) && [45, '45'].includes(businessType2)
    },
    // 是否显示加盟相关字段
    // 1.新增字段【是否有店面】【店面总面积】【意向经营业务】【意向客户分类】。
    // 字段展示在【业务部门】后面。
    // 2.当一二级业务类型为【咨询-加盟信息】时，展示以上新增的字段。
    showJoinIn() {
      const { businessType1, businessType2 } = this.formData
      return [1, '1'].includes(businessType1) && [6, '6'].includes(businessType2)
    },
    // 产品类型是否必填
    productTypeRequired() {
      return this.$isClient() && ![6, '6'].includes(this.formData.businessType2)
    }
  },
  watch: {
    productTypeOption: {
      handler(newV, oldV) {
        if (newV.length && (this.$route.query.id || this.$route.query.workOrderNo)) {
          this.getLocalProductType(this.formData.productType)
        }
      },
      immediate: true
    },
    functionalSpaceStore: {
      handler(newV, oldV) {
        if (newV.length && (this.$route.query.id || this.$route.query.workOrderNo)) {
          this.getLocalProductCategory(this.formData.functionalSpace)
        }
      },
      immediate: true
    },
    orderData: {
      // 来自于来电弹屏的订单数据
      handler() {
        this.$nextTick(() => {
          const set = this.$set.bind(this, this.formData)
          const d = this.orderData
          if (Object.keys(d).length <= 0) return
          if (d.online) {
            set('buyChannel', '1')
            set('orderCode', d.pcode)
            set('nickname', d.buyer)
            set('onlinePlatformCode', d.platCode)
            set('onlinePlatformName', d.platName)

            const filtersRaw = [{ id: 'platformCode', value: d.platCode, property: 'platformCode', operator: 'like' }]
            const data = json2FormData({
              filtersRaw: JSON.stringify(filtersRaw)
            })
            getStoreInfoB2CECO(data).then(res => {
              this.onlineShopOption = res.data.records
              for (const item of this.onlineShopOption) {
                if (item.code === d.storeCode) {
                  set('onlineShopCode', item.code)
                  set('onlineShopName', item.name)
                  break
                }
              }
            })
            set('officeCode', d.officeCode)
            set('officeName', d.officeName)
            set('disCode', d.serviceCode)
            set('disName', d.serviceName)
            set('province', d.receiverProvinceId)
            set('provinceName', d.receiverProvince)
            this.getLocalCityInfo(this.formData.province)
            set('city', d.receiverCityId)
            set('cityName', d.receiverCity)
            this.getLocalCountyInfo(this.formData.city)
            set('county', d.receiverDistrictId)
            set('countyName', d.receiverDistrict)
            this.getLocalStreetInfo(this.formData.county)
            set('street', d.receiverTownId)
            set('streetName', d.receiverTown)
            set('detailAddress', d.receiverAddress)

            set('contactName', d.receiver)
            set('contactPhone', d.receiverPhone)

            // 配送方式
            set('deliveryMethod', this.$numToString(this.serMap[d.serviceMode]))

            set('orderTime', d.bookTime ? parseTime(d.bookTime) : '') // 购买时间
            set('deliveryTime', d.deliveryTime ? parseTime(d.deliveryTime) : '') // 预约送货时间
          } else {
            set('buyChannel', '2')
            set('disId', d.distributorId)
            set('officeCode', d.officeCode)
            set('officeName', d.officeName)
            set('disCode', d.distributorCode)
            set('disName', d.distributorName)
            set('shopCode', d.storeCode)
            set('shopName', d.storeName)
            set('detailAddress', d.deliveryAddress)
            set('orderCode', d.saleOrderCode)
            set('deliveryMethod', this.$numToString(this.delMap[d.deliveryType]))

            set('contactName', d.customerName)
            set('contactPhone', d.contactNumber)

            // 处理地址统一通过msc的id
            this.handleAddress()
          }
          this.buyChannelHandle({ dictCode: this.formData.buyChannel })
        })
      },
      immediate: true
    },
    provinceNameOption() {
      // 处理地址统一通过msc的id
      this.handleAddress()
    },
    callTel: {
      handler(nv) {
        this.$set(this.formData, 'contactPhone', this.callTel)
        if (nv) {
          const data = this.channelTypeOption
          for (const item of data) {
            if (item.dictName === '电话') {
              this.$set(this.formData, 'channelType', item.dictCode)
              return
            }
          }
        }
      },
      immediate: true
    },
    // 查询是否有未完结工单
    'formData.contactPhone'(v) {
      if (/^1\d{10}$/.test(v)) {
        this.checkHaveWorkOrder(v)
      }
    },
    // 同步recordId到dRecordId
    recordId: {
      handler() {
        this.dRecordId = this.recordId
      },
      immediate: true
    },
    showJoinIn: {
      handler(v) {
        const t = ![1, '1', 2, '2'].includes(this.formData.channelType)
        if (v && t) {
          this.$set(this.formData, 'channelType', '')
        }
      }
    }
  },
  async created() {
    Object.keys(this.bottomAuth).forEach(k => {
      // if (k === 'abnormal') {
      // this.$set(this.bottomAuth, k, false)
      // } else {
      this.$set(this.bottomAuth, k, true)
      // }
    })

    // 获取省份
    getAdminiDiv({}).then(res => {
      this.provinceNameOption = res.data
    })
    await this.getDataDict({ type: 'channelType', ditctType: 'CHANNEL_TYPE' }) // 联系渠道
    await this.getDataDict({ type: 'complaintCause', ditctType: 'COMPLAINTS_REASON' }) // 投诉原因
    await this.getDataDict({ type: 'productType', ditctType: 'PRODUCT_TYPE' }) // 产品类型
    await this.getDataDict({ type: 'functionalSpace', ditctType: 'FUNCTIONAL_SPACE' }) // 功能空间
    await this.getDataDict({ type: 'productCategory', ditctType: 'PRODUCT_CATEGORY' }) // 产品品类

    if (this.$isShop()) {
      // 当组织编码为电商管理部（组织编码为：25）的时候，购买渠道默认展示为电商(1)
      this.$set(this.formData, 'buyChannel', '1')
      this.buyChannelHandle({ dictCode: '1' })
    }
    this.$set(this.formData, 'urgencyDegree', '1')// 紧急程度默认为正常(1)

    // 当query带有id时获取保存、完结工单数据
    this.getWorkOrderData()
  },
  mounted() {
    // ===== 外呼回访 =====
    this.callOutVisitDataHandler()
  },
  methods: {
    // 获取保存、完结工单数据
    getWorkOrderData() {
      const to = this.$route
      const state = to.query.state
      // 保存状态工单
      if (state === 0 || state === '0') {
        if (Object.keys(to.query).indexOf('id') !== -1 || Object.keys(to.query).indexOf('workOrderNo') !== -1) {
          Object.keys(this.formData).forEach((key) => {
            this.$set(this.formData, key, '')
          })
          this.orderType = to.query.type
          this.getLocalWorkInfo(to.query.id)
        }
      }
      // 完结状态工单
      if (state === 3 || state === '3') {
        if (Object.keys(to.query).indexOf('id') !== -1) {
          Object.keys(this.formData).forEach((key) => {
            this.$set(this.formData, key, '')
          })
          this.copyWorkOrderInfo(to.query.id, 'copy')
        }
      }
    },
    // 联系电话改变后，检查是否有未完结工单
    checkHaveWorkOrder(v) {
      const id = this.$route.query.id || this.$route.query.workOrderNo
      if (v === '' || !v || this.page === 'call' || id) {
        return
      }
      getHaveWorkOrder(v).then(res => {
        if (res.data.total > 0) {
          return this.$confirm(`该联系人已存在${res.data.total}个未完结工单，是否确定创建此工单？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.closeCurrentTag()
          })
        } else {
          return Promise.resolve()
        }
      })
    },
    // 处理门店地址
    handleAddress() {
      const set = this.$set.bind(this, this.formData)
      const d = this.orderData
      if (Object.keys(d).length <= 0) return
      // 门店订单地址id有两种表示方式，用长度区分
      if (d.provinceId && d.provinceId.length > '510000000000'.length) {
        set('province', d.provinceId)
        set('provinceName', d.provinceName)
        this.getLocalCityInfo(d.provinceId)
        set('city', d.cityId)
        set('cityName', d.cityName)
        this.getLocalCountyInfo(this.formData.city)
        set('county', d.countyId)
        set('countyName', d.countyName)
        this.getLocalStreetInfo(this.formData.county)
        set('street', d.streetId)
        set('streetName', d.streetName)
        return
      }
      let t = false
      for (const p of this.provinceNameOption) {
        if (p.code === d.provinceId) {
          set('province', p.id)
          t = true
          break
        }
      }
      if (!t) return
      t = false
      this.getLocalCityInfo(this.formData.province).then(res => {
        for (const c of this.cityNameOption) {
          if (c.code === d.cityId) {
            set('city', c.id)
            t = true
            break
          }
        }
        if (!t) return Promise.reject()
      }).then(() => {
        t = false
        return this.getLocalCountyInfo(this.formData.city).then(res => {
          for (const c of this.countyNameOption) {
            if (c.code === d.countyId) {
              set('county', c.id)
              t = true
              break
            }
          }
          if (!t) return Promise.reject()
        })
      }).then(() => {
        this.getLocalStreetInfo(this.formData.county).then(res => {
          for (const s of this.streetNameOption) {
            if (s.code === d.streetId) {
              set('street', s.id)
              break
            }
          }
        })
      })
    },
    /**
     * 获取数据字典
     */
    getDataDict({ type, ditctType }) {
      const dictTypeCode = ditctType
      const appCode = 'call-center'
      const domainCode = 'marketing'
      const parmas = {
        dictTypeCode,
        appCode,
        domainCode
      }
      getDictByType(parmas).then(res => {
        const data = res.data || []
        if (Array.isArray(data)) {
          // data.sort(this.arraySort('dictCode'))
          if (type === 'channelType') {
            // 联系渠道
            this.channelTypeOption = data
            if (this.callTel || this.$route.name === 'Display') {
              // CC-来电弹屏页-工单创建页-【联系渠道】默认值为“电话”
              for (const item of data) {
                if (item.dictName === '电话') {
                  this.$set(this.formData, 'channelType', item.dictCode)
                  return
                }
              }
            } else if (this.$isClient() || this.$inGroup(20)) {
              // 当业务组为接线组（业务组编码为：20）的时候，联系渠道默认展示为电话(1)
              this.$set(this.formData, 'channelType', '1')
            } else if (this.$isShop()) {
              // 当组织为电商管理部（组织编码为：25）的时候，联系渠道默认展示为电商平台(5)
              this.$set(this.formData, 'channelType', '5')
            }
          }
          if (type === 'complaintCause') {
            // 投诉原因
            this.complaintCauseStore = data
          }
          if (type === 'productType') {
            // 产品类型
            this.productTypeOption = data.map(e => {
              e.dictCode = Number(e.dictCode)
              return e
            })
          }
          if (type === 'functionalSpace') {
            // 功能空间
            this.functionalSpaceStore = data.map(e => {
              e.dictCode = Number(e.dictCode)
              return e
            })
          }
          if (type === 'productCategory') {
            // 产品品类
            this.productCategoryStore = data
          }
        }
      })
    },
    // 切换购买渠道
    buyChannelHandle(row) {
      // 处理方案
      this.$refs.handleScheme && this.$refs.handleScheme.getDictInfo(true)

      const val = row ? Number(row.dictCode || 0) : ''
      if (Number(val || 0) === 1) {
        // 购买渠道为电商时
        if (this.callTel || this.$route.name === 'Display') {
          // CC-来电弹屏页-工单创建页-【联系渠道】默认值为“电话”
          for (const item of this.channelTypeOption) {
            if (item.dictName === '电话') {
              this.$set(this.formData, 'channelType', item.dictCode)
              break
            }
          }
        } else {
          // CC-服务工单-工单创建页-【联系渠道】则根据创建人的组织展示默认值，创建人组织为“电商管理部”，默认值为“电商平台”
          const orgName = (this.$store.getters.userCache && this.$store.getters.userCache.organization) || ''
          if (orgName === '电商管理部') {
            const dict = this.channelTypeOption.find(v => v.dictName === '电商平台')
            this.$set(this.formData, 'channelType', (dict && dict.dictCode) || '')
          }
        }
      }

      if (!this.$route.query.id && !this.$route.query.workOrderNo) {
        // 购买渠道为电商时，产品类型默认为电商（仅创建工单时默认）
        this.$set(this.formData, 'productType', Number(val || 0) === 1 ? 3 : '')
        this.productTypelChange(this.formData.productType || '')
      }
      // 根据购买渠道，获取初始化业务类型
      (async() => {
        await this.initBusinessType(val)
        this.setBusinessTypeBygroup32()
      })()

      // 来电弹屏选择购买渠道不清空数据
      if (this.callTel || this.$route.name === 'Display') return
      // 清空数据, 编辑数据不操作
      const { state, id, workOrderNo } = this.$route.query || {}
      if (state === undefined && id === undefined && workOrderNo === undefined) {
        this.$set(this.formData, 'orderCode', '')
        this.$set(this.formData, 'onlinePlatformCode', '')
        this.$set(this.formData, 'onlinePlatformName', '')
        this.$set(this.formData, 'onlineShopCode', '')
        this.$set(this.formData, 'onlineShopName', '')
        this.$set(this.formData, 'officeName', '')
        this.$set(this.formData, 'officeCode', '')
        this.$set(this.formData, 'ecOrderNumber', '')
        this.clearChange()
      }
    },
    /**
     * 加载本地未完成工单详细
     */
    getLocalWorkInfo(id, type) {
      let ajaxName = getByIdWorkOrderRecord
      // 通过工单编号获取
      if (this.$route.query.workOrderNo && type === undefined) {
        ajaxName = getWorkOrderByCode
        id = this.$route.query.workOrderNo
      }
      ajaxName(id).then(async(res) => {
        if (res.success === 1) {
          const data = { ...res.data }
          this.isClear = false
          if (type === 'copy') {
            delete data.id
            delete data.workOrderCode
            delete data.workOrderState
          }
          // 处理产品信息
          data.productInfoDTOList = data.productInfoDTOList.filter(e => {
            delete e.workOrderCode
            delete e.workOrderId
            // return !!e.productId
            // 62275   创建工单和来电弹屏创建工单页面-产品信息新增手动录入产品信息和必填设置 手动新增的没有productId
            return true
          })
          if (data.id) this.reloadInfo.id = data.id
          this.reloadInfo.workOrderCode = data.workOrderCode || ''
          this.reloadInfo.workOrderState = data.workOrderState || ''
          const toStringArr = ['urgencyDegree', 'channelType', 'productCategory', 'compensationFee', 'hasShop'] // 需转换为字符串的字段
          const multToStringArr = ['serviceFeeType', 'feeType', 'compensationCause', 'complaintCause', 'complaintObject', 'customerDisapprovalCause', 'productProblem', 'handleScheme', 'paymentMode', 'repairsReason'] // 多选值转换为字符串的字段
          const numToStrArr = ['businessType1', 'businessType2', 'deliveryMethod'] // 数字转换为字符串
          const ignoreKey = 'productCode productName productMode'.split(' ')
          const strToArr = 'bizType'.split(' ')
          Object.keys(this.formData).forEach((key) => {
            if (ignoreKey.includes(key)) {
              return
            }
            if (toStringArr.indexOf(key) !== -1) {
              if (data[key] || data[key] === 0) this.$set(this.formData, key, String(data[key]) || '')
            } else if (multToStringArr.indexOf(key) !== -1) {
              let tmpArr = []
              if (data[key] && data[key].length) {
                tmpArr = data[key].map(v => String(v) || '')
              }
              this.$set(this.formData, key, tmpArr)
            } else if (numToStrArr.indexOf(key) !== -1) {
              this.$set(this.formData, key, this.$numToString(data[key]))
            } else if (strToArr.indexOf(key) !== -1) {
              this.$set(this.formData, key, (data[key] || '').split(','))
            } else {
              this.$set(this.formData, key, data[key] || '')
            }
          })

          if (Array.isArray(data.annexList) && data.annexList.length) {
            this.annexList = data.annexList.map(list => {
              list['name'] = list.fileName
              list['url'] = list.filePath
              return list
            })
          }
          if (Array.isArray(data.processingList)) this.processingList = data.processingList
          if (type === 'copy') {
            // this.annexList = []
            this.processingList = []
          }
          await this.getLocalBusinessType(data.buyChannel, data.businessType1)
          this.getLocalProductType(data.productType)
          this.getLocalProductCategory(data.functionalSpace)
          this.getLocalDealerInfo(data.officeCode, data.disCode)

          this.businessTypeTwoChange(this.formData.businessType2, false, false)
          // 重新获取处理方案数据
          this.$nextTick(() => {
            this.$refs.handleScheme && this.$refs.handleScheme.getDictInfo(true)
          })
        }
      })
    },
    // 复制工单
    copyWorkOrderInfo(id, type) {
      this.getLocalWorkInfo(id, type)
    },
    /**
     * 根据购买渠道查找业务类型
     * @param {String} buyChannel  购买渠道
     * @param {String} businessType1 一级业务类型
    */
    async getLocalBusinessType(buyChannel, businessType1) {
      const parmas = {
        channelCode: buyChannel,
        businessType: businessType1
      }
      if (!buyChannel) {
        this.businessType1Option = []
      } else {
        // 查询一级业务类型
        await searchBusinessByChannel(buyChannel).then(res => {
          if (res.success === 1) {
            this.businessType1Option = res.data || []
          }
        })
      }
      if (!buyChannel || !businessType1) {
        this.businessType2Option = []
      }
      // 查找二级业务类型
      await searchBusinessTwoByChannel(parmas).then(res => {
        if (res.success === 1) {
          this.businessType2Option = res.data
        }
      })
    },
    // 加载本地功能空间数据
    getLocalProductType(dictCode) {
      this.$nextTick(() => {
        this.productTypelChange(dictCode, false)
      })
    },
    // 加载本地产品种类
    getLocalProductCategory(sDictCode) {
      this.$nextTick(() => {
        this.functionalSpaceChange(sDictCode, false)
      })
    },
    // 加载本地经销商
    getLocalDealerInfo(code, disCode) {
      if (code && disCode) {
        return getDealerInfo({ officeCode: code, codeOrName: disCode }).then(res => {
          if (res.success === 1) {
            const obj = res.data.records.find(list => {
              return list.code === disCode
            })
            if (obj === undefined || obj === 'undefined') return
            this.formData.disId = obj.id
          }
        })
      }
    },
    // 加载本地城市
    getLocalCityInfo(id) {
      return getAdminiDiv({ id: id }).then(res => {
        if (res.success === 1) {
          this.cityNameOption = res.data
        }
      })
    },
    // 加载本地街道
    getLocalStreetInfo(id) {
      return getAdminiDiv({ id: id }).then(res => {
        if (res.success === 1) {
          this.streetNameOption = res.data
        }
      })
    },
    // 加载本地区县
    getLocalCountyInfo(id) {
      return getAdminiDiv({ id: id }).then(res => {
        if (res.success === 1) {
          this.countyNameOption = res.data
        }
      })
    },
    // 清空产品加载内容
    clearProCodeChange() {
      this.$set(this.formData, 'productName', '')
      this.$set(this.formData, 'productMode', '')
    },
    proCodeEnter(productCode) {
      if (productCode === '' || productCode === null) {
        // this.$message('请输入产品编码')
        return false
      }
      this.clearProCodeChange()
      getProductInfo(productCode).then((res) => {
        if (res.success === 1) {
          const { name, productModelName } = res.data
          this.$set(this.formData, 'productName', name)
          this.$set(this.formData, 'productMode', productModelName)
        }
      })
    },
    // 清空订单加载内容
    clearChange() {
      const clearArr = ['nickname', 'onlinePlatformCode', 'onlinePlatformName', 'onlineShopCode', 'onlineShopName', 'officeCode', 'officeName', 'disId', 'disCode', 'disName', 'shopCode', 'shopName', 'province', 'provinceName', 'city', 'cityName', 'county', 'countyName', 'street', 'streetName', 'detailAddress', 'deliveryMethod', 'orderTime', 'deliveryTime']
      // 非来电弹屏和呼出才可以修改客户姓名和电话
      if (this.page !== 'call') {
        clearArr.push('contactName', 'contactPhone')
      }
      clearArr.forEach(item => {
        this.$set(this.formData, item, '')
      })
      this.formData.afterSalesCall = ''
      this.shopCallTel = []
      // 刷新表单验证队列
      setTimeout(() => { this.$refs['formOrder'].clearValidate() }, 0)
    },
    // 平台单号变化
    handleOrderCodeChange() {
      this.clearChange()
      this.$set(this.formData, 'ecOrderNumber', '')
    },
    /**
     * 查询B2C订单详细
     */
    contactEnter(orderCode) {
      if (orderCode === '' || orderCode === null || orderCode === undefined) {
        // this.$message('请输入订单编号')
        return false
      }
      this.clearChange()
      if (orderCode.indexOf('LTK') === 0 || orderCode.indexOf('LSK') === 0) {
        this.setContact()
        this.getRetailDetailByCode(orderCode)
        return false
      }
      this.isLoading = true
      Promise.all([getOrderDetailPCode({ pcode: orderCode }), productInfoByPCode(orderCode)]).then(res => {
        const d = (res[1].data || []).filter(e => ['01', '0'].includes(e.orderType))
        let t = d.filter(e => !!e.deliveryTime)
        if (this.formData.ecOrderNumber) {
          t = t.filter(e => this.formData.ecOrderNumber.includes(e.code))
        }

        if (d.length > 0) {
          const data = res[0].data || {}
          Object.assign(data, t.length > 0 ? t[0] : d[0])
          this.setOrderInfo(data)
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 设置订单信息
    async setOrderInfo(orderInfo) {
      const { code, buyer, receiver, receiverPhone, platCode, platName, storeCode, storeName, logisticsMode } = orderInfo
      let { serviceName, serviceCode, officeName, officeCode } = orderInfo
      const { receiverProvince, receiverCity, receiverDistrict, receiverTown, receiverAddress } = orderInfo
      const { serviceId, serviceMode, bookTime, deliveryTime } = orderInfo
      let { receiverProvinceId, receiverCityId, receiverDistrictId, receiverTownId } = orderInfo
      this.formData.nickname = buyer
      if ([1, '1', '02'].includes(logisticsMode)) {
        await electronicCheck(code).then(async res => {
          if (!res.data || !res.data.servicerCode) {
            return this.$msgbox({
              title: '服务商变更提示',
              message: '当前订单所属区域无服务商，工单经销商数据以订单为准'
            }).then(() => {
              serviceCode = ''
              serviceName = ''
            })
          }
          if (res.data.servicerCode !== serviceCode) {
            return this.$msgbox({
              title: '服务商变更提示',
              message: `当前订单所属区域服务商已变更为【${res.data.servicerName}】，工单是否替换为此经销商？`,
              showCancelButton: true
            }).then(() => {
              serviceCode = res.data.servicerCode
              serviceName = res.data.servicerName
              officeCode = res.data.agencyCode
              officeName = res.data.agencyName
            }).catch(() => {
              return
            })
          }
        }).catch(msg => {
          return this.$msgbox({
            title: '服务商变更提示',
            message: 'ECO四级地址配送表接口调用失败，工单经销商数据以订单为准。'
          })
        })
      }
      // 来电弹屏和呼出不修改
      if (this.page !== 'call') {
        this.formData.contactName = receiver // 联系人
        this.formData.contactPhone = receiverPhone // 联系电话
      }
      this.setContact()
      this.formData.onlinePlatformCode = platCode // 电商平台Code
      this.formData.onlinePlatformName = platName // 电商平台名称
      this.formData.onlineShopCode = storeCode // 电商Code
      this.formData.onlineShopName = storeName // 电商店铺

      this.formData.officeName = officeName // 办事处名称
      this.formData.officeCode = officeCode // 办事处Code
      serviceCode && this.checkDisStatus(serviceCode, true).then(async({ isMatch }) => {
        if (!isMatch) {
          // if (isMatch) {
          this.$set(this.formData, 'disId', serviceId)
          this.$set(this.formData, 'disName', serviceName) // 经销商名称
          this.$set(this.formData, 'disCode', serviceCode) // 经销商Code
        } else {
          let { receiverProvinceCode, receiverCityCode, receiverDistrictCode, receiverTownCode } = orderInfo
          // 系统根据订单的省市区县去四级地址配送表内寻找对应的经销商带出来
          if (!receiverProvinceCode) receiverProvinceCode = await this.findProvinceCode(receiverProvinceId)
          if (!receiverCityCode) receiverCityCode = await this.findCityCode(receiverProvinceId, receiverCityId)
          if (!receiverDistrictCode) receiverDistrictCode = await this.findCountyCode(receiverCityId, receiverDistrictId)
          if (!receiverTownCode) receiverTownCode = await this.findStreetCode(receiverDistrictId, receiverTownId)
          const data = new FormData()
          data.append('provinceCode', receiverProvinceCode)
          data.append('provinceName', receiverProvince)
          data.append('cityCode', receiverCityCode)
          data.append('cityName', receiverCity)
          data.append('districtCode', receiverDistrictCode)
          data.append('districtName', receiverDistrict)
          data.append('townCode', receiverTownCode)
          data.append('townName', receiverTown)
          data.append('platformCode', platCode)
          data.append('storeCode', storeCode)
          getDealerMatch(data).then(res => {
            // console.log(res, '=============')
            if (!res.data) return Promise.reject('未匹配到经销商!')
            const d = res.data
            this.$set(this.formData, 'disId', d.serviceId1)
            this.$set(this.formData, 'disName', d.serviceName1) // 经销商名称
            this.$set(this.formData, 'disCode', d.serviceCode1) // 经销商Code
          }).catch(msg => {
            this.$message.warning(msg)
          })
        }
      })

      this.formData.deliveryMethod = this.$numToString(this.serMap[serviceMode]) // 配送方式
      this.formData.orderTime = bookTime ? parseTime(bookTime) : '' // 购买时间
      this.formData.deliveryTime = deliveryTime ? parseTime(deliveryTime) : '' // 预约送货时间

      if (receiverProvinceId && receiverProvinceId.length === 12) receiverProvinceId = await this.findProvinceId(receiverProvinceId)
      this.formData.province = receiverProvinceId // 省份Id
      this.formData.provinceName = receiverProvince // 省份名称

      if (receiverCityId && receiverCityId.length === 12) receiverCityId = await this.findCityId(receiverProvinceId, receiverCityId)
      this.formData.city = receiverCityId // 城市ID
      this.formData.cityName = receiverCity // 城市名称

      if (receiverDistrictId && receiverDistrictId.length === 12) receiverDistrictId = await this.findCountyId(receiverCityId, receiverDistrictId)
      this.formData.county = receiverDistrictId // 县区ID
      this.formData.countyName = receiverDistrict // 县区名称

      if (receiverTownId && receiverTownId.length === 12) receiverTownId = await this.findStreetId(receiverDistrictId, receiverTownId)
      this.formData.street = receiverTownId // 街道ID
      this.formData.streetName = receiverTown // 街道名称

      this.formData.detailAddress = receiverAddress // 地址

      if (serviceCode) {
        this.checkShopNum(serviceCode)
      }
    },
    checkDisStatus(disCode, isEco) { // isEco 是否电商订单
      return checkDistributorByDisCode(disCode).catch(res => {
        if (isEco) {
          return this.$msgbox({
            title: '提示',
            message: `【${res.data.name}】已停业，是否为您匹配新的经销商？`,
            type: 'info',
            showCancelButton: true
          }).then(() => {
            return Promise.resolve({ disDetail: res, isMatch: true })
          })
        }
        return Promise.reject(res)
      })
    },
    /**
     * 查询TOP订单详细
     */
    getRetailDetailByCode(saleOrderCode) {
      if (saleOrderCode) {
        this.isLoading = true
        getRetailDetail(saleOrderCode).then(async(res) => {
          this.isLoading = false
          if (res.success === 1 && Object.keys(res.data).length) {
            const { officeCode, officeName, distributorId, distributorCode, distributorName, storeCode, storeName } = res.data
            const { provinceName, cityName, countyName, streetName, orderReceiverAddress, deliveryType, makeOrderTime, arrangeAppointmentTime } = res.data
            let { provinceId, cityId, countyId, streetId } = res.data
            this.formData.officeName = officeName // 办事处名称
            this.formData.officeCode = officeCode // 办事处Code
            this.checkDisStatus(distributorCode).then(() => {
              this.$set(this.formData, 'disId', distributorId)
              this.$set(this.formData, 'disName', distributorName) // 经销商名称
              this.$set(this.formData, 'disCode', distributorCode) // 经销商Code
            })
            this.formData.shopCode = storeCode // 门店Code
            this.formData.shopName = storeName // 门店名称

            this.formData.deliveryMethod = this.$numToString(this.delMap[deliveryType]) // 配送方式
            this.formData.orderTime = makeOrderTime // 购买时间
            this.formData.deliveryTime = arrangeAppointmentTime // 预约送货时间

            // provinceId 为 Code时执行
            if (provinceId && provinceId.length === 12) provinceId = await this.findProvinceId(provinceId)
            this.formData.province = provinceId
            this.formData.provinceName = provinceName // 省份名称

            // cityId 为 Code时执行
            if (cityId && cityId.length === 12) cityId = await this.findCityId(provinceId, cityId)
            this.formData.city = cityId // 城市ID
            this.formData.cityName = cityName // 城市名称

            // 当countId 为 Code时执行
            if (countyId && countyId.length === 12) countyId = await this.findCountyId(cityId, countyId)
            this.formData.county = countyId // 县区ID
            this.formData.countyName = countyName // 县区名称

            // streetId 为 Code时执行
            if (streetId && streetId.length === 12) streetId = await this.findStreetId(countyId, streetId)
            this.formData.street = streetId // 街道ID
            this.formData.streetName = streetName // 街道名称

            this.formData.detailAddress = orderReceiverAddress // 地址

            if (storeCode) {
              this.getSalesCall({ shopCode: storeCode })
            } else if (distributorCode) {
              this.checkShopNum(distributorCode)
            }
          }
        }, () => {
          this.isLoading = false
        })
      }
    },
    handleOnConfirm(ecOrderNumbers, firstOrderCode, selection) {
      this.$set(this.formData, 'ecOrderNumber', ecOrderNumbers.join(','))
      this.contactEnter(firstOrderCode)
    },
    // 电商单号可以输入多个
    handleEBusicontactEnter(ecCode) {
      if (ecCode === '' || ecCode === undefined || ecCode === null) {
        return false
      }
      getPlateCodeByEcCode(ecCode).then(res => {
        this.$set(this.formData, 'orderCode', res.msg)
        this.contactEnter(this.formData.orderCode)
      })
    },
    // 获取经销商对应的办事处
    findOfficeInfo(disCode) {
      getOfficeDetail(disCode).then(res => {
        if (res.success === 1) {
          this.formData.officeName = res.data.name
          this.formData.officeCode = res.data.code
        }
      })
    },
    /**
     * 初始化业务类型1
     * @param {String/Number} channelCode  购买渠道
     */
    initBusinessType(channelCode) {
      this.formData.businessType1 = ''
      this.formData.businessType1Name = ''
      this.businessType1Option = []

      this.formData.businessType2 = ''
      this.formData.businessType2Name = ''
      this.businessType2Option = []

      this.formData.bpmDeptCode = ''
      this.formData.bpmDeptName = ''
      if (!channelCode) return
      // 根据购买渠道查询一级业务类型
      return searchBusinessByChannel(channelCode).then(res => {
        if (res.success === 1) {
          // res.data.sort(this.arraySort('relationCode'))
          this.businessType1Option = res.data || []
        }
      })
    },

    businessTypeChange(val) {
      // 根据购买渠道和一级业务类型查询二级业务类型
      const obj = this.businessType1Option.find(v => v.businessType === val)
      this.$set(this.formData, 'businessType1Name', obj && obj.businessTypeName || '')
      this.formData.businessType2 = ''
      this.formData.businessType2Name = ''
      this.businessType2Option = []

      this.formData.bpmDeptCode = ''
      this.formData.bpmDeptName = ''
      if (!val) {
        this.businessType2Option = []
        return
      }
      const parmas = {
        channelCode: this.formData.buyChannel,
        businessType: this.formData.businessType1
      }
      return searchBusinessTwoByChannel(parmas).then(res => {
        if (res.success === 1) {
          // res.data.sort(this.arraySort('relationCode'))
          this.businessType2Option = res.data
        }
      })
    },
    /**
     * 查找二级业务类型=》投诉原因
     * @param {String} dictCode 经销商编码
     * @param {Boolean} clear  切换业务类型时，是否清空关联项(投诉原因,默认业务部门),编辑时首次加载不清空
     * */
    businessTypeTwoChange(dictCode, clear = true, setHandleScheme = true) {
      const obj = this.businessType2Option.find(v => v.businessTypeTwo === dictCode)
      this.$set(this.formData, 'businessType2Name', obj && obj.businessTypeTwoName || '')

      // 设置处理方案
      if (setHandleScheme) {
        this.setHandleScheme(this.formData.businessType1, dictCode)
      }

      // 设置工单对接人联系电话
      this.setAfterSalesCall()

      if (clear) {
        this.setBpmDepartDefault(clear)
      }

      // 根据二级业务类型查找对应的投诉原因
      if (clear) {
        this.$set(this.formData, 'complaintCause', [])
        this.complaintCauseOption = []
      }
      if (Number(this.formData.businessType1 || 0) !== 2) return
      if (dictCode === '') {
        return
      }
      const data = TCCMap[dictCode]
      if (!data || data.length === 0) {
        return
      }
      this.complaintCauseOption = this.complaintCauseStore.filter(e => {
        return data.includes(Number(e.dictCode || 0))
      })
    },
    // 根据一二级业务类型设置处理方案
    setHandleScheme(businessType1, businessType2) {
      if ([3, '3'].includes(businessType1) && [15, '15'].includes(businessType2)) {
        // 当一级业务类型为3【业务办理】二级业务类型选择为15【费用赔付】时，
        // 处理方案默认展示为1【客服即时解决】和2【费用赔付
        this.$set(this.formData, 'handleScheme', ['1', '2'])
      } else if ([3, '3'].includes(businessType1) && [19, '19'].includes(businessType2)) {
        // 57693   字段关联调整：处理方案-换货
        // 当一级业务类型为业务办理，二级业务类型为换货时，处理方案默认为：换货。
        this.$set(this.formData, 'handleScheme', ['10'])
      } else if ([31, '31'].includes(businessType2)) {
        this.$set(this.formData, 'handleScheme', ['6'])
      } else {
        this.$set(this.formData, 'handleScheme', ['1'])
      }
    },
    // 根据一级业务类型和二级业务类型查询默认责任部门
    setBpmDepartDefault(clear = true) {
      if (clear) {
        this.formData.bpmDeptCode = ''
        this.formData.bpmDeptName = ''
      }

      const parmas = {
        businessType: this.formData.businessType1,
        businessTypeTwo: this.formData.businessType2
      }
      searchBusinessDefaultDept(parmas).then(res => {
        if (res.success === 1 && res.data) {
          // res.data.sort(this.arraySort('relationCode'))
          // 设置默认责任部门
          this.formData.bpmDeptCode = res.data.dept || ''
          this.formData.bpmDeptName = res.data.deptName || ''
        }
      })
    },
    // 电商工单二期 售后业务自动取售后联系人电话，非那几个售后业务且购买渠道为电商，取电商业务联系人
    setAfterSalesCall() {
      if (!this.formData.shopCode && !this.formData.disCode) {
        return
      }
      const params = {}
      this.formData.shopCode && (params.shopCode = this.formData.shopCode)
      this.formData.disCode && (params.disCode = this.formData.disCode)
      this.getSalesCall(params).then(data => {
        if (!data || data.length === 0) {
          return
        }

        const t = [31, 32, 33, 18, 19, '31', '32', '33', '18', '19'].includes(this.formData.businessType2)
        if (t) {
          this.$set(this.formData, 'afterSalesCall', data[0].contactPhone)
        }
        if (!t && [1, '1'].includes(this.formData.buyChannel)) {
          this.$set(this.formData, 'afterSalesCall', data[0].ecContactPhone)
        }
      })
    },
    /**
     * 查找产品类型->功能空间
     */
    productTypelChange(dictCode, clear = true) {
      if (clear) {
        this.$set(this.formData, 'functionalSpace', '')
        this.$set(this.formData, 'productCategory', '')
        this.functionalSpaceOption = []
        this.productCategoryOption = []
      }
      if (dictCode === '') {
        return
      }
      const data = PSCMap[dictCode]
      if (!data) {
        return
      }
      this.functionalSpaceOption = this.functionalSpaceStore.filter(e => {
        if (e.dictCode in data) {
          return true
        }
        return false
      })
    },
    /**
     * 查找功能空间->产品品类
     */
    functionalSpaceChange(dictCode, clear = true) {
      if (clear) {
        this.productCategoryOption = []
        this.$set(this.formData, 'productCategory', '')
      }
      if (dictCode === '') {
        return
      }
      const p = PSCMap[this.formData.productType]
      if (!p) {
        return
      }
      const c = p[dictCode]
      if (!c) {
        return
      }
      this.productCategoryOption = this.productCategoryStore.filter(e => {
        if (c.includes(e.dictCode) || c.includes(Number(e.dictCode))) {
          return true
        }
        return false
      })
    },
    /**
     * Object类型数组排序
     */
    arraySort(field) {
      return (a, b) => {
        const val1 = a[field]
        const val2 = b[field]
        return val1 - val2
      }
    },
    /**
     * 获取电商店铺及电商平台对应值
     */
    onlinePlatformChange(plat) {
      const code = plat.code
      if (code === '') {
        this.$set(this.formData, 'onlineShopCode', '')
        this.onlineShopOption = []
        return
      }
      this.$set(this.formData, 'onlineShopCode', '')

      const filtersRaw = [{ id: 'platformCode', value: code, property: 'platformCode', operator: 'like' }]
      const data = json2FormData({
        filtersRaw: JSON.stringify(filtersRaw)
      })

      getStoreInfoB2CECO(data).then(res => {
        if (res.success === 1) this.onlineShopOption = res.data.records
      })
    },

    // 办事处值改变时
    officeSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['officeCode']) }, 0)
      this.resetOfficeName()
    },
    // 经销商值改变时
    disSelectChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['disCode']) }, 0)
      this.resetDisName()
      if (!this.formData.officeCode && data.code) this.findOfficeInfo(data.code)
      if (data && data.name) this.checkShopNum(data.name)
    },
    // 售后电话改变时
    afterSalesCallChange(data) {
      setTimeout(() => { this.$refs['formOrder'].validateField(['afterSalesCall']) }, 0)
    },
    // 门店值改变时
    selectChange(data) {
      this.resetShopInfo()
      if (data && data.shopCode) this.getSalesCall({ shopCode: data.shopCode })
    },
    // 查询该经销商下是否有门店
    checkShopNum(disCode) {
      const params = new FormData()
      params.append('page', 1)
      params.append('rows', 2)

      getMscInfoShop({ customerCodes: disCode }, params).then(res => {
        if (res.success === 1) {
          if (res.data.total === 0) {
            this.getSalesCall({ disCode: this.formData.disCode })
          }
        }
      })
    },
    /**
     * 获取门店对应的联系方式
     */
    getSalesCall(obj) {
      if (Object.keys(obj).length === 0) {
        return
      }
      this.shopCallTel = []
      const paramsArr = ArrayFormat(obj)
      const pageInfo = new FormData()
      pageInfo.append('rows', 20)
      pageInfo.append('page', 1)
      if (Array.isArray(paramsArr) && paramsArr.length) pageInfo.append('filtersRaw', JSON.stringify(paramsArr))
      return getShopAfterInfo(pageInfo).then(res => {
        if (res.success === 1) {
          const data = res.data.records
          data.forEach((item, index) => {
            if (item.contactPhone) {
              item.value = item.contactPhone
              item.name = item.afterSaleContact
            } else {
              data.splice(index, 1)
            }
          })
          if (Array.isArray(data) && data.length === 1) {
            this.formData.afterSalesCall = data[0].value
          } else {
            this.formData.afterSalesCall = ''
          }
          this.shopCallTel = data
          return data
        } else {
          this.shopCallTel = []
          return Promise.reject(res)
        }
      })
    },
    /**
     * 匹配门店相应的联系方式
     */
    afterCallSearchAsync(queryString, callback) {
      const shopCallTel = this.shopCallTel
      const results = queryString ? shopCallTel.filter(this.createStateFilter(queryString)) : shopCallTel

      callback(results)
    },
    /**
     * JS-filter Function
     */
    createStateFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    /**
     * 省份初始化加载->find ID
     */
    findProvinceId(code) {
      return getAdminiDiv({}).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.code === code) return item.id
          }
        }
      })
    },
    /**
     * 获取对应城市 ID
     */
    findCityId(parentId, code) {
      if (parentId === '' || code === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.code === code) return item.id
          }
        }
      })
    },
    /**
     * 获取对应区县 ID
     */
    findCountyId(parentId, code) {
      if (parentId === '' || code === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.code === code) return item.id
          }
        }
      })
    },
    /**
     * 获取街道 ID
     */
    findStreetId(parentId, code) {
      if (parentId === '' || code === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.code === code) return item.id
          }
        }
      })
    },

    // 根据省市区id获取编码
    /**
     * 省份初始化加载->find Code
     */
    findProvinceCode(id) {
      return getAdminiDiv({}).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.id === id) return item.code
          }
        }
      })
    },
    /**
     * 获取对应城市 Code
     */
    findCityCode(parentId, id) {
      if (parentId === '' || id === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.id === id) return item.code
          }
        }
      })
    },
    /**
     * 获取对应区县 Code
     */
    findCountyCode(parentId, id) {
      if (parentId === '' || id === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.id === id) return item.code
          }
        }
      })
    },
    /**
     * 获取街道 Code
     */
    findStreetCode(parentId, id) {
      if (parentId === '' || id === '') return
      return getAdminiDiv({ id: parentId }).then(res => {
        if (res.success === 1) {
          const list = [...res.data]
          for (const item of list) {
            if (item.id === id) return item.code
          }
        }
      })
    },
    // 检查文件总大小
    checkFileSizeGt100() {
      let sumSize = 0
      this.imageList.forEach(e => {
        sumSize += e.size
      })
      // 限制100m
      if (sumSize > 100 * 1024 * 1024) {
        this.$message.error('上传文件总大小不能大于100M！')
        return true
      }
      return false
    },
    // 如果是来弹屏则获取recordId
    getRecordId() {
      if (this.getRecordIdFun instanceof Function) {
        return this.getRecordIdFun().then(async res => {
          this.dRecordId = res
          return true
        })
      }
      return Promise.resolve()
    },
    // 单击保存按钮
    saveOrderHandler() {
      this.saveOrder().then(res => {
        if (this.page === 'call') {
          this.disabled1 = true
          return // 呼叫弹屏直接关闭不再新建创建工单页面
        }
        this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews, visitedQueue }) => {
          // 57461   电商-售中客服组，创建工单页面调整需求
          if (this.isCreate && !this.isTask && this.isSMCSD) {
            this.$router.push({ name: 'CreateOrder', query: { createdAt: new Date().getTime() }})
            return
          }
        })
      })
    },
    // 保存
    saveOrder(msg = '确定要保存该工单?', resMsg = '工单保存成功') {
      if (this.checkFileSizeGt100()) {
        return Promise.reject('')
      }

      // 移除表单项的校验结果
      this.$refs['formOrder'].clearValidate()

      return this.formValidate().then((res) => {
        return this.$msgbox({
          title: '保存',
          showCancelButton: true,
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          message: msg,
          type: 'warning'
        }).then(async() => {
          // 先尝试获取通话id
          await this.getRecordId()
          const paramsObj = new FormData()
          const params = { ...this.formData }

          for (const file of this.imageList) {
            paramsObj.append('files', file)
          }
          // 如果是弹屏则添加通话记录id
          if (this.dRecordId) {
            params.serialNumber = this.dRecordId
          }
          // 复制工单
          const { id, state } = this.$route.query
          if (id && Number(state) === 3) {
            params.copyId = id
          }
          // 处理加盟信息
          if (this.showJoinIn) {
            if (params.bizType instanceof Array) {
              params.bizType = params.bizType.join(',')
            }
            if (params.shopArea === undefined || params.shopArea === '' || params.shopArea === null) {
              params.shopArea = '0'
            }
          } else {
            delete params.hasShop
            delete params.shopArea
            delete params.bizType
            delete params.potentialType
          }
          paramsObj.append('jsonStr', JSON.stringify(params))

          this.saveOrderLoading = true
          return postWorkOrderRecord(paramsObj).then(res => {
            this.saveOrderLoading = false
            if (res.success === 1) {
              this.formData.id = res.msg
              // if (res.msg) this.reloadOrderInfo(res.msg)  // 第2540行关闭了改标签
              this.$message({
                message: resMsg,
                type: 'success'
              })
              this.$emit('workOrderSuccess')
              if (this.page === 'call') this.pageState = false
              this.$emit('on-success', res.msg)
              !(this.isSMCSD && this.isCreate) && this.closeCurrentTag(true)
              return res
            }
          }).catch(() => {
            this.saveOrderLoading = false
            return Promise.reject(false)
          })
        })
      })
    },
    // 责任部门派单
    dispatchcOrderEnableOpen() {
      return new Promise((resolve, reject) => {
        if (this.checkFileSizeGt100()) {
          return reject()
        }
        Object.assign(this.formRules, {
          officeCode: [],
          disCode: [],
          handleScheme: []
        })
        // 移除表单项的校验结果
        this.$refs['formOrder'].clearValidate()

        this.formValidate().then((valid) => {
          console.log('valid', valid)
          if (valid) {
            return resolve()
          }
          return reject('完善表单项')
        }).catch(() => {
          return reject('表单信息未完善')
        })
      })
    },
    // 同步工单
    syncOrderEnableOpen() {
      return new Promise((resolve, reject) => {
        this.$refs.formOrder.validateField(['callContent', 'customerServiceOpinion'], errMsg => {
          if (errMsg) { return reject(errMsg) }
          return resolve()
        })
      })
    },
    // 接收岗位
    handleReceivePostOnConfirm(handlerPosts, ccPosts, resovle, reject) {
      this.formData.handlerPosts = handlerPosts
      this.formData.ccPosts = ccPosts

      this.saveOrder('确定要派单该岗位？', '工单派单接收人岗位成功！').then(() => {
        resovle()
        this.disabled1 = true
      }).catch((err) => {
        // 表单验证不通过
        if (err === false) {
          resovle()
          this.$message.warning('请检查必填项!')
          return
        }
        reject()
      })
    },
    // 上报异常
    abnormalReportEnableOpen() {
      return new Promise((resolve, reject) => {
        this.$refs.formOrder.validateField(['productType'], errMsg => {
          if (errMsg) { return reject(errMsg) }
          return resolve()
        })
      })
    },
    // 刷新动态值（附件，工单编号）
    reloadOrderInfo(id) {
      if (!id) {
        this.$message({
          message: '工单信息刷新失败',
          type: 'warning'
        })
        return
      }
      getByIdWorkOrderRecord(id).then(res => {
        if (res.success === 1) {
          const { id, workOrderCode, workOrderState, annexList } = res.data
          this.reloadInfo.id = id
          this.reloadInfo.workOrderCode = workOrderCode
          this.reloadInfo.workOrderState = workOrderState
          if (Array.isArray(annexList) && annexList.length) {
            // this.isClear = true
            this.annexList = []
            this.annexList = annexList.map(list => {
              list['name'] = list.fileName
              list['url'] = list.filePath
              return list
            })
          }
        }
      })
    },
    // 分配给经销商-指派任务
    assignDealer(type) {
      if (this.checkFileSizeGt100()) {
        return
      }
      if (type === 'office') {
        Object.assign(this.formRules, { officeCode })
        setTimeout(() => { this.$refs.formOrder.validateField(['officeCode']) }, 0)
      } else {
        Object.assign(this.formRules, { officeCode: [] })
        setTimeout(() => { this.$refs.formOrder.validateField(['officeCode']) }, 0)
      }
      if (type === 'dis') {
        Object.assign(this.formRules, { disCode })
        setTimeout(() => { this.$refs.formOrder.validateField(['disCode']) }, 0)
      } else {
        Object.assign(this.formRules, { disCode: [] })
        setTimeout(() => { this.$refs.formOrder.validateField(['disCode']) }, 0)
      }

      Object.assign(this.formRules, { handleScheme: [] })
      setTimeout(() => { this.$refs.formOrder.validateField(['handleScheme']) }, 0)

      // 移除表单项的校验结果
      this.$refs['formOrder'].clearValidate()
      this.formValidate().then((valid) => {
        // FIXME:验证经销商和门店是否正常营业
        let messageTitle = '办事处'
        if (type === 'office') messageTitle = '办事处'
        if (type === 'dis') messageTitle = '经销商'
        if (type === 'shop') messageTitle = '责任部门'
        this.$msgbox({
          title: '指派',
          showCancelButton: true,
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning',
          message: `该工单确定要指派给${messageTitle}？`
        }).then(async() => {
          this.dispatchOrder(type)
        })
      })
    },
    /**
     * 完结工单
     */
    putFinishClick() {
      if (this.checkFileSizeGt100()) {
        return
      }

      // 处理方案必填条件： 一级业务类型为投诉/纠纷(2)和业务办理（3）时必填
      const businessType1 = Number(this.formData.businessType1 || 0)
      const schemeMust = businessType1 === 2 || businessType1 === 3

      Object.assign(this.formRules, {
        handleScheme: schemeMust ? handleSchemeRule : [],
        officeCode: [],
        disCode: []
      })
      setTimeout(() => { this.$refs.formOrder.validateField(['handleScheme']) }, 0)

      this.$refs['formOrder'].clearValidate()
      this.formValidate().then(async() => {
        // 先尝试获取通话id
        await this.getRecordId()

        // FIXME:验证经销商和门店是否正常营业
        const paramsObj = new FormData()
        const params = { ...this.formData }

        for (const file of this.imageList) {
          if (file) paramsObj.append('files', file)
        }
        // 如果是弹屏则添加通话记录id
        if (this.dRecordId) {
          params.serialNumber = this.dRecordId
        }
        // 复制工单
        const { id, state } = this.$route.query
        if (id && Number(state) === 3) {
          params.copyId = id
        }
        // 处理加盟信息
        if (this.showJoinIn) {
          if (params.bizType instanceof Array) {
            params.bizType = params.bizType.join(',')
          }
          if (params.shopArea === undefined || params.shopArea === '' || params.shopArea === null) {
            params.shopArea = '0'
          }
        } else {
          delete params.hasShop
          delete params.shopArea
          delete params.bizType
          delete params.potentialType
        }
        paramsObj.append('jsonStr', JSON.stringify(params))
        this.$msgbox({
          title: '完结确认',
          showCancelButton: true,
          cancelButtonText: '返回修改',
          confirmButtonText: '确认无误',
          message: '请确认当前<span style="color: red;">【处理方案】</span>是否准确！',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          this.putFinishLoading = true
          return putFinish(paramsObj).then(res => {
            if (res.success === 1) {
              this.formData.id = res.msg
              this.$message({
                message: '工单完结成功',
                type: 'success'
              })
              this.$emit('workOrderSuccess')
              if (this.page === 'call') this.pageState = false

              // 57461   电商-售中客服组，创建工单页面调整需求
              if (this.isSMCSD && this.isCreate) {
                if (this.page === 'call') {
                  this.disabled1 = true
                  return // 呼叫弹屏直接关闭不再新建创建工单页面
                }
                this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews, visitedQueue }) => {
                  this.$router.push({ name: 'CreateOrder', query: { createdAt: new Date().getTime() }})
                })
              } else {
                this.closeCurrentTag(true)
              }
            }
          }).finally(() => { this.putFinishLoading = false })
        })
      })
    },
    // 同步工单
    syncSuceess() {
      // 只禁用上报异常操作
      Object.keys(this.bottomAuth).forEach(k => {
        if (k === 'abnormal') {
          this.$set(this.bottomAuth, k, false)
        } else {
          this.$set(this.bottomAuth, k, true)
        }
      })
      this.$emit('workOrderSuccess')
      if (this.page === 'call') this.pageState = false
      // this.closeCurrentTag()
    },
    // 上报异常
    abnormalSuccess() {
      this.$set(this.bottomAuth, 'abnormal', false)
      this.$emit('workOrderSuccess')
      if (this.page === 'call') this.pageState = false
      this.closeCurrentTag()
    },
    // 关怀
    careSuccess() {
      this.$emit('workOrderSuccess')
      if (this.page === 'call') this.pageState = false
      this.closeCurrentTag()
    },
    // 上传附件成功
    onSuccessHandle(res, file, fileList) {
      // console.log('upload')
      // console.log(res, file, fileList)
    },
    // 文件改变时
    onChangeHandle(file, fileList) {
      this.isClear = false
      this.imageList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    // 删除附件
    beforeRemoveHandle(file, fileList) {
      return this.$msgbox({
        title: '删除',
        message: '确认删除该附件？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        if (file.status === 'success') {
          const fileObj = { ...file }
          delete fileObj.name
          delete fileObj.url
          return deleteAnnex(fileObj).then(res => {
            this.$message({
              message: '附件删除成功',
              type: 'success'
            })
            return 'success'
          })
        }
      })
    },
    // 删除成功
    removeHandle(file, fileList) {
      this.imageList = fileList.map((list) => {
        return list.raw
      }).filter(e => {
        return e !== undefined
      })
    },
    /**
     * 重置办事处以下信息
     */
    resetOfficeName() {
      this.$set(this.formData, 'disCode', '')
      this.$set(this.formData, 'disName', '')
      this.$set(this.formData, 'shopCode', '')
      this.$set(this.formData, 'shopName', '')
      this.$set(this.formData, 'afterSalesCall', '')
      this.shopCallTel = []
    },
    /**
     * 重置经销商以下相关信息
     */
    resetDisName() {
      this.$set(this.formData, 'shopCode', '')
      this.$set(this.formData, 'shopName', '')
      this.$set(this.formData, 'afterSalesCall', '')
      this.shopCallTel = []
    },
    /**
     * 重置门店信息
     */
    resetShopInfo() {
      this.$set(this.formData, 'afterSalesCall', '')
      this.shopCallTel = []
    },
    // 关闭当前标签页
    closeCurrentTag(isClose) {
      // 保存操作后关闭当前页签
      if (isClose) {
        if (this.page === 'call') {
          this.disabled1 = true
          return // 呼叫弹屏直接关闭不再新建创建工单页面
        }
        this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews, visitedQueue }) => {
          // 如果query不带有id参数，则打开新的创建工单界面
          if (!this.$route.query.id && !this.$route.query.workOrderNo && !this.isTask) {
            this.$router.push({ name: 'CreateOrder', query: { createdAt: new Date().getTime() }})
            return
          }
          const latestView = visitedQueue.pop()
          if (latestView) {
            this.$router.push(latestView)
          } else {
            this.$router.push('/')
          }
        })
      }
      // 呼叫弹屏跳转不关闭当前标签页
      if (this.page === 'call') {
        return
      }
    },
    // 客户联系电话  发送短信
    contactTpSms(phone) {
      const tel = phone !== undefined ? phone : this.formData.contactPhone
      if (tel === '' || tel === undefined) {
        this.$message.warning(`请输入手机号码!`)
        return
      }
      if (!/^1\d{10}/.test(tel)) {
        this.$message.warning(`【${tel}】不是手机号码!`)
        return
      }
      const callTel = tel.trim()
      const workOrderCode = ''
      const content = ''
      this.$router.push({ name: 'SMSSend', query: { callTel, workOrderCode, content }})
    },
    // 外呼
    callOutHandle(phone) {
      const tel = phone !== undefined ? phone : this.formData.contactPhone
      if (tel === '' || tel === undefined) {
        this.$message.warning(`请输入联系电话!`)
        return
      }
      this.$refs.callOut.debounceCallOut(tel)
    },
    // 指派工单
    async  dispatchOrder(type, receiverList) {
      // 先尝试获取通话id
      await this.getRecordId()

      const paramsObj = new FormData()

      const params = { ...this.formData }

      if (type === 'office') params.receiveSystem = 'UIP' // 办事处
      if (type === 'dis') params.receiveSystem = 'PANDA' // 经销商
      if (type === 'shop') {
        // 责任部门
        if (!receiverList || receiverList.length === 0) {
          this.$message.warning(`请选择责任部门接收人!`)
          return
        }
        params.receiveSystem = 'ECO'
        params.receiverDTOList = receiverList
      }
      for (const file of this.imageList) {
        paramsObj.append('files', file)
      }
      // 如果是弹屏则添加通话记录id
      if (this.dRecordId) {
        params.serialNumber = this.dRecordId
      }
      // 复制工单
      const { id, state } = this.$route.query
      if (id && Number(state) === 3) {
        params.copyId = id
      }
      // 处理加盟信息
      if (this.showJoinIn) {
        if (params.bizType instanceof Array) {
          params.bizType = params.bizType.join(',')
        }
        if (params.shopArea === undefined || params.shopArea === '' || params.shopArea === null) {
          params.shopArea = '0'
        }
      } else {
        delete params.hasShop
        delete params.shopArea
        delete params.bizType
        delete params.potentialType
      }
      paramsObj.append('jsonStr', JSON.stringify(params))
      this.isLoading = true
      postDispatch(paramsObj).then(res => {
        if (res.success === 1) {
          this.formData.id = res.msg
          this.$message({
            message: '工单指派成功',
            type: 'success'
          })
          this.isLoading = false
          this.bottomAuth.save = false // 禁用保存操作
          this.disabled1 = true // 禁止编辑
          if (type === 'office' || type === 'dis') {
            this.bottomAuth.office = false // 禁用办事处指派
            this.bottomAuth.dis = false // 禁用经销商指派
          } else {
            this.bottomAuth.shop = false
            this.$refs.refDispatch.closeDialog()
          }
          this.bottomAuth.abnormal = true // 异常上报可操作
          this.$emit('workOrderSuccess')
          if (this.page === 'call') this.pageState = false

          // 57461   电商-售中客服组，创建工单页面调整需求
          if (this.isSMCSD && this.isCreate) {
            if (this.page === 'call') {
              this.disabled1 = true
              return // 呼叫弹屏直接关闭不再新建创建工单页面
            }
            this.$store.dispatch('tagsView/delView', this.$route).then(({ visitedViews, visitedQueue }) => {
              this.$router.push({ name: 'CreateOrder', query: { createdAt: new Date().getTime() }})
            })
          } else {
            this.closeCurrentTag(true)
          }
        } else {
          this.isLoading = false
        }
      }).finally(() => { this.isLoading = false })
    },
    // 责任部门指派操作
    submitReciverDispatch(receiverList) {
      this.dispatchOrder('shop', receiverList)
    },
    // 表单校验统一提示
    formValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.formOrder.validate((result, message) => {
          if (result) {
            resolve(result)
          } else {
            reject(reject)
            const msg = Object.values(message).map(e => {
              return e.map(m => m.message).join('<br>')
            }).join('<br>')
            this.$message.warning({
              message: msg,
              dangerouslyUseHTMLString: true
            })
          }
        })
      })
    },
    // 外呼回访数据处理
    callOutVisitDataHandler() {
      if (!this.isTask) return
      this.formData.callBackObjectId = this.taskData.id
      if (this.taskData.taskType === '1') {
        this.$set(this.formData, 'buyChannel', '1')
        this.buyChannelHandle({ dictCode: '1' })
      } else if (this.taskData.taskType === '2') {
        this.$set(this.formData, 'buyChannel', '2')
        this.buyChannelHandle({ dictCode: '2' })
      }
      this.$nextTick(() => {
        if (!this.taskData.orderCode) return
        setTimeout(() => {
          this.$set(this.formData, 'orderCode', this.taskData.orderCode)
          if (this.taskData.taskType === '1') {
            setTimeout(() => {
              this.$refs.selectOrderList.handleClick()
            }, 10)
          } else if (this.taskData.taskType === '2') {
            this.contactEnter(this.formData.orderCode)
          }
        }, 0)
      })
    },
    // 外呼回访设置联系人
    setContact() {
      if (this.isTask) {
        if (!this.formData.contactName) {
          this.$set(this.formData, 'contactName', this.taskData.customerName)
        }
        if (!this.formData.contactPhone) {
          this.$set(this.formData, 'contactPhone', this.visitForm.customerPhone)
        }
      }
    },
    // 当业务组为32-电商-售中客服科时，
    // 服务工单-创建工单内：一级业务类型默认1-展示咨询，二级业务类型默认展示45-物流进度。
    // 57206   创建工单页面字段默认值需求

    // 58666   售中客服创建工单业务类型默认项调整
    // 基于任务57590进行修改：技能组包含 电商-售中客服服务科  的用户，
    // 创建工单页面默认：一级业务类型：业务办理，二级业务类型：送装服务
    async setBusinessTypeBygroup32() {
      if (this.isSMCSD && this.isCreate) {
        this.$set(this.formData, 'businessType1', '3')
        await this.businessTypeChange('3')
        this.$set(this.formData, 'businessType2', '22')
        this.businessTypeTwoChange('22', true, true)
      }
    },
    // 验证产品信息
    validateProductListInfo(r, v, c) {
      if ([1, '1'].includes(this.formData.buyChannel) && [15, 18, 19, 31, 33, '15', '18', '19', '31', '33'].includes(this.formData.businessType2)) {
        if (!v || v.length <= 0) {
          c('至少要有一行产品数据')
          return
        } else {
          for (let i = 0; i < v.length; i++) {
            const t = v[i]
            if (!t.productCode) {
              c(`请输入第${i + 1}行产品编码`)
              return
            }
            if (!t.productName) {
              c(`请输入第${i + 1}行产品名称`)
              return
            }
            if (!t.productCategory) {
              c(`请输入第${i + 1}行产品型号`)
              return
            }
            if (!t.handleNum) {
              c(`请输入第${i + 1}行处理数量`)
              return
            }
          }
        }
        c()
      } else {
        c()
      }
    },
    // 只有购买渠道为电商才有售后退货
    // 过滤退换货原因
    filterHandleScheme(data) {
      setTimeout(() => {
        let t = this.formData.handleScheme || []
        const t1 = this.formData.buyChannel || ''
        if (![1, '1'].includes(t1) && t.some(e => [14, '14'].includes(e))) {
          t = [...t]
          const i = t.findIndex(e => [14, '14'].includes(e))
          if (i >= 0) {
            t.splice(i, 1)
            this.$set(this.formData, 'handleScheme', t)
          }
        }
      }, 300)
      return data.filter(e => {
        if ([14, '14'].includes(e.dictCode) && ![1, '1'].includes(this.formData.buyChannel)) {
          return false
        }
        return true
      })
    }

  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/mixin.scss";
.create-order {
  // background-color: white;
  /deep/ .el-input-group__append{
    padding: 0 4px;
  }
}
.create-order {
  /deep/ .el-autocomplete {
    width: 100%;
  }
  /deep/ .my-autocomplete {
    & li {
      display: flex;
      justify-content: space-between;
      padding: 10px;
      padding: 7px;

      .tel {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .name {
        font-size: 12px;
        color: #b4b4b4;
      }
      .highlighted .name {
        color: #ddd;
      }
    }
  }
}
// .create-order .content-wrap /deep/ .el-autocomplete-suggestion li {
//   padding: 0 10px !important;
//   line-height: 20px !important;
//   display: flex !important;
//   justify-content: space-between !important;
// }
.create-order .content-wrap /deep/ .el-form .el-row .el-col-4 {
  width: 20% !important;
}
.create-order .content-wrap /deep/ .custom-title {
  padding: 0;
}
.create-order .content-wrap /deep/ .order-top {
  padding: 10px 0;
}
.create-order .content-wrap /deep/ .custom-title h3 {
  font-weight: bold;
  font-size: 14px;
  color: #16BC83;
}
.create-order .content-wrap /deep/ .order-list {
  font-size: 12px;
  line-height: 18px;
}

.create-order .content-wrap /deep/ .order-list p:first-child {
  width: 20%;
  flex: 0 0 20% !important;
}
.create-order .content-wrap /deep/ .order-list p:nth-child(2) {
  width: 20%;
  flex: 0 0 20% !important;
}
.create-order .content-wrap /deep/ .order-list p:nth-child(3) {
  width: 25%;
  flex: 0 0 25% !important;
}
.create-order .content-wrap /deep/ .order-list p:last-child {
  width: 25%;
  flex: 0 0 25% !important;
}
// 短信图标
.sms{
  color:#00926d;
  cursor: pointer;
}
</style>
